How to structure Python code for fewer headaches

Status
Not open for further replies.

S. Carton

Ars Scholae Palatinae
937
Don't listen to the naysayers DavlinLotze, they just enjoy the headaches that stem from idiomatically-structured python code.

Calling exec() on code you represent as strings and building your own versions of import and class are brilliant moves. Here are a few tools you might find useful in your quest to futher improve your programs' structure:

1) Directly manipulate the python abstract syntax tree using the ast module http://docs.python.org/2/library/ast.html . This will let you improve upon python's semantics; write code that looks like python but with the semantics YOU want!

2) I noticed you dislike how python exceptions work. You can use the send() coroutine facility introduced in http://www.python.org/dev/peps/pep-0342/ together with ast manipulation to create your own custom control flows. For example, you could identify blocks in the ast and wrap them in generators that are invoked by your own autogenerated scheduler, so making exceptions behave as you'd like becomes a piece of cake. The potential for structure using this approach is frankly breathtaking.

Please continue informing us about your evolving structuring adventures.
 

Agathos

Ars Praefectus
3,558
Subscriptor
DavlinLotze":2bghmih1 said:
Well, apart from the hassle of creating untold numbers of custom exceptions (at least one for each function?) this would still catch recursion or mutual recursion when I don't want to. Alternately I could create an exception type that takes a function as a parameter, and then raise MyException("Problem with...", this_func) but again, I still wouldn't be able to differentiate recursion.

I bet you could write a function decorator (call it @exceptiontracking) that automagically creates a new exception for each function, but also keeps track of whether that function was called by itself, or by another @exceptiontracking function, and treats those cases differently.

I wouldn't do this, of course, but you might love it.

This thread is great.
 

ahankinson

Wise, Aged Ars Veteran
117
I never program with other people, so I don't give a darn about language conventions, stylistic conventions, or programming idiomatically. If I knew every computer language ever made, it's possible I might have chosen something other than Python, but I've used enough programming languages to get a good feel for what's out there. I'm not really concerned if you cringe at the way I (ab)use python. You should see how I've (ab)used other languages. Python's dynamic nature at least makes some types of changes easier, even if it has a rather pathetic set of control structures (no do-while, goto, gosub/return, select case, etc. - I list only ones that exist in other languages - not all the ones that exist in my mind that I've never seen in a programming language.)

Yet here you are, with a title that suggests that even your own idiomatic Python code has given you headaches in the past. You can certainly write your own way of doing it, but you came here for help. You're saying "I keep hitting myself with this hammer, and can't figure out why my head hurts!" and others are saying "THEN STOP HITTING YOURSELF WITH A HAMMER."

I think it's also wrong to suggest that you never code with other people. You *always* code with other people -- yourself in the past, yourself in the present, and yourself in the future. Structuring your code so that it follows standard idioms isn't just because somebody somewhere thought that they knew best -- it's because it's essentially documentation for yourself later, when you've forgotten how your code works.

Also, I think you're trolling when you complain about Python's control structures. do/while is essentially a while with a conditional break; goto is stupid in most contexts; gosub/return is just a function call; and select/case is essentially if/elif.

But just for fun, here's an un-nested Python switch statement that you can incorporate into your un-nested Python classes.

Implementation
Code:
class switch(object):
    def __init__(self, check):
        self.check = check

    def case(self, condition, function):
        if condition == self.check:
            return function(y)

Usage
Code:
y = 'foo'
resfn = lambda x: 'condition is ' + x
resfn = is_bar = is_baz = is_foo
f = switch(y)
f.case('bar', is_bar)
f.case('baz', is_baz)
f.case('foo', is_foo)

There's bonus points for modularity here, since you don't even need to keep the 'case' statements anywhere near the switch, like you need to in regular Python 'if/elif' statements or other inferior languages. You can call it anywhere in your code where your 'switch' is in scope and it will still work.
 

DavlinLotze

Ars Scholae Palatinae
830
ShuggyCoUk":26xy5ubu said:
Then, regardless of your opinion on anything else in the thread, you must surely agree that your Title is grossly misleading.

What you are doing is *guaranteed* to cause more headaches, and you have no intention of changing much of it.

There's simply no point trying to assist you here, your code is a train wreck. I can only hope it is never used by anyone else as you imply.
You can consider that more than an implication - it's an outright statement: I don't code with other people, never have, and don't plan on it. My title wasn't intended to be misleading, as I seriously wanted answers about how to make it less of a headache for me. The answers I got didn't provide the structure I was looking for, so that's when I wrote my own module, and mentioned it. I said upfront that I didn't expect to convince you career programmers it was a good idea - just that it works for me.

I'm also seriously worried at your ability to cogently design a decent DSL given what you believe is worth doing in order to achieve it.
Don't worry - be happy. I appreciate any well-intentioned help, and even some of the sarcastic jokes, as it adds to the discussion, but ultimately you're not responsible for what or how I choose to code in my spare time. But if that doesn't ease your "worry", all I can tell you is that my program is coming along nicely. It loads user input and parses it into the various objects in memory very well and gives me excellent user-friendly messages when there's a problem. That was the easy part - the harder part, which will be ongoing, is creating the infrastructure to work with those primitives and then start expanding the language.

Maarten":26xy5ubu said:
the reason that the OP is not working together with others (likely including himself) is not because he doesn't want to, but because all others have run away.
Like I said - never have, and don't plan to. I've seen the work of even accomplished programmers, and it drives me as crazy as my code would drive them. People express things in different ways. Part of my goal with my own language is to give me a better way of expressing myself in concepts that make sense to me.

ahankinson":26xy5ubu said:
Yet here you are, with a title that suggests that even your own idiomatic Python code has given you headaches in the past. You can certainly write your own way of doing it, but you came here for help.
I started this thread very early in the game. I understood python much less at the time, and I was frustrated with what I considered silly scoping rules. Now that I've written that module, I'm quite content with using python, and I find more frustration with the files I haven't switched over yet.

I'm sure you thought your switch/case was funny, but it completely misses the spirit of a select/case. A switch statement is designed to let you mention a value just once, then branch based on conditions about that value. It reduces repetition. (Your code isn't runnable, but I'm guessing your "resfn" on the third line was intended to be at the end of the line.) Your code merely substitutes restating a 'y' with restating an 'f'. Not to mention that you lose all context when you have to call a separate function, and without a goto, there's no easy way to break out of the flow. Similarly, losing the context is what distinguishes gosub/return from a call to a completely different routine. (At least that's how I remember it working - it's been many years.) There are many cases in which I could write much simpler easier-to-maintain functions with gosub/return. Sure, Python is turing complete and it has some convenient features, but having a rich set of control structures is not one of them.

S. Carton: I know you were kidding, but thanks for the links - it could be interesting to study if I get a chance.

Agathos":26xy5ubu said:
I bet you could write a function decorator (call it @exceptiontracking) that automagically creates a new exception for each function, but also keeps track of whether that function was called by itself, or by another @exceptiontracking function, and treats those cases differently.
Something like that brushed my mind, but I hadn't given it much thought. The part I bolded is where I don't see how I could do that. How can a function tell what it was called by? The traceback module lets you get a function name, but it doesn't give you a reference to the function object itself, which is the only way you could really tell them apart, since any number of functions can share the same name.

Alamout: Out of your five posts in this thread, only one of them is constructive. But that's a better record than some - keep up the good work. :)

LordHunter317":26xy5ubu said:
exceptions are not a bug detection mechanism!
This is what I'm trying to understand you on. I'm well aware that exceptions can't find all bugs and that they are no substitute for proper code review and testing, but do you really mean it when you say that exceptions don't help programmers catch bugs? Exceptions indicate (among other things, but quite frequently) errors. Bugs, in many cases, cause errors. Why would you say that exceptions don't detect bugs? Are you saying that it's better to not implement integrity checks, such as type-checking arguments, and just let the bug go on and do what it will lead to - just let it either result in undefined/erroneous behavior or kill the program via natural consequences instead of through a manual integrity check? What about assertions? (implemented in python via exceptions) Is Wikipedia wrong when it says: "assertions provide a very powerful tool in debugging."? I've always considered assertions, type-checking, and various other integrity checks as fundamental to writing code in which bugs have a harder time of going unnoticed. Do I have that all wrong?
 

Jonathon

Ars Legatus Legionis
17,646
Subscriptor
DavlinLotze":2iiyt3td said:
LordHunter317":2iiyt3td said:
exceptions are not a bug detection mechanism!
This is what I'm trying to understand you on. I'm well aware that exceptions can't find all bugs and that they are no substitute for proper code review and testing, but do you really mean it when you say that exceptions don't help programmers catch bugs? Exceptions indicate (among other things, but quite frequently) errors. Bugs, in many cases, cause errors. Why would you say that exceptions don't detect bugs? Are you saying that it's better to not implement integrity checks, such as type-checking arguments, and just let the bug go on and do what it will lead to - just let it either result in undefined/erroneous behavior or kill the program via natural consequences instead of through a manual integrity check? What about assertions? (implemented in python via exceptions) Is Wikipedia wrong when it says: "assertions provide a very powerful tool in debugging."? I've always considered assertions, type-checking, and various other integrity checks as fundamental to writing code in which bugs have a harder time of going unnoticed. Do I have that all wrong?
Exceptions aren't an integrity check, at least not in that sense of the term. Exceptions are meant to indicate exceptional events (things outside your control) in the normal, correct operation of your code: things like a TCP connection being reset unexpectedly, a file not being found, the system running out of memory, or malformed user input coming into your program. That some of these cases can also be triggered by buggy code is purely coincidental (and means that they can be helpful during debugging, but they're not intended as a debugging tool primarily).

Assertions (and other development-time conveniences like type checking) are for debugging (and are typically turned off in production for performance reasons). These are the things you use in development (especially in Python, which doesn't do much static checking of anything beyond syntax) to verify that your program is in the correct state at the correct time. That they're implemented using exceptions in Python is just an artifact of the language; exceptions in Python provide a way for the assertion to terminate the program, indicating the line where the assertion failed and the reason why it failed. They shouldn't be used for control flow, nor should you normally try to catch them-- assertions are a debugging tool, not something you're using at run time.
 

LordHunter317

Ars Legatus Legionis
22,394
Subscriptor
Jonathon":vsdrq4t2 said:
These are the things you use in development (especially in Python, which doesn't do much static checking of anything beyond syntax)
Not even that. Modules are parsed at runtime, which means you get the syntax error at runtime. However, the interpreter is two-pass, so generally you can't execute code in a module and get a syntax error[1].

[1] It might well be always, but I don't want to issue that as a guarantee when I'm not 100% sure of it myself.
 

ahankinson

Wise, Aged Ars Veteran
117
Hey now, my code is perfectly runnable. And you probably spent more time explaining it than I did writing it. :)

The point was that I *could* write something like that, but it would be really, really dumb. Like, not indenting blocks. And not using contexts properly.

If you need to break a flow with a goto, you're doing it wrong. Like Blacken says, you seem like you actually want to be writing BASIC.
 

herko

Tone down Your Control issues.
7,012
Moderator
Someone complained that gosub was missing. We can't have that.

Code:
def gosub(fn, *args, **kwargs):
    return fn(*args, **kwargs)

Invocation:

def add(a, b):
    return a+b

>>>gosub(add, 3, 4)
7

In related news,
a22082d9d307065851b2ed5876d25dde.jpg
 

herko

Tone down Your Control issues.
7,012
Moderator
In the same vein, I found a very clever, although limited (intra-function) recipe for goto in python.

Python goto

It requires a decorator, which the OP doesn't like, but perhaps that can be solved by invoking it like a regular function. What the decorator does is disassemble the function, NOP the labels, replace the goto statements with JUMP_ABSOLUTE to the labels, and reassemble.

Usage:
Code:
@goto
def loopy(max):
    counter=0
    label .here
    print counter
    if counter==max:
        return
    counter+=1
    goto .here
   
Instead of using the decorator, you can use the function itself, which might suit the OP better. 
loopy=goto(loopy)
 

herko

Tone down Your Control issues.
7,012
Moderator
ahankinson":ct38xbiy said:
And someone has filled the huge void in Python where it was lacking goto.

This oversight has been corrected: http://entrian.com/goto/

Great minds think alike :D although the recipe I found claims to be 60x faster, and more pythonic to boot.

Which begs the question of why do you care about pythonicism if you are writing a goto library in the first place, but there you go.
 

herko

Tone down Your Control issues.
7,012
Moderator
ahankinson":1mif2avo said:
I think the key to understanding the Python goto library is at the very top of the page:

The "goto" module was an April Fool's joke, published on 1st April 2004. Yes, it works, but it's a joke nevertheless. Please don't use it in real code!

Yes, and in contrast mine is *serious business*. It could perhaps maybe be useful if you squint and want to implement a state machine. Or perhaps, if you want to structure your code "for fewer headaches".
 

DavlinLotze

Ars Scholae Palatinae
830
Jonathon and LordHunter317: Thanks for the comments on exceptions - they were clear and helpful.

You may be interested to know that I added iterator functionality to the Serialization, and I also used a generator function for a similar thing that traverses over the object's parts.

ahankinson":1gjtu795 said:
And someone has filled the huge void in Python where it was lacking goto.

This oversight has been corrected: http://entrian.com/goto/

I'd seen that one, but hadn't seen the one herko mentioned. As helpful as it might be, I haven't taken the time to figure out how they work or attempted to use them.

I'm on cloud nine today, as my program has finally reached a point well beyond any of my previous attempts - it's actually working and useful. Still very ugly and undeveloped with no GUI, but the core is largely there.
 

Alamout

Ars Legatus Legionis
27,285
It's not working because the body of the lambda (the call to 'i') isn't evaluated until you call the lambda, and by the time you do that the 'i' has reached its last value, the function h(). So all three members of funcs reference the same object.

You're looking to write a closure. You could do it this way (I apologize to everyone else for enabling god-knows-what):
Code:
>>> f = lambda: 'f'
>>> g = lambda: 'g'
>>> h = lambda: 'h'
>>> funcs = [lambda: i() for i in (f,g,h)]
>>> funcs[0]()
'h'
>>> funcs[2]()
'h'
>>> funcs[1]()
'h'
>>> funcs = [lambda i=i: i() for i in (f,g,h)]
>>> funcs[0]()
'f'
>>> funcs[1]()
'g'
>>> funcs[2]()
'h'
The default value is evaluated during the comprehension, and thus captures the current value of i at that time.
 

sid0

Ars Tribunus Militum
2,364
DavlinLotze":3pt2vx4s said:
I must not understand list comprehensions as well as I thought:
The problem is that list comprehensions don't create a fresh binding every iteration, but instead (since the bound variables leak out into the outer scope) keep using the same variable for multiple bindings. C# < 5 has the same misfeature.

Every programmer has hit this at some point in their lives. Consider it a rite of passage.
 

DavlinLotze

Ars Scholae Palatinae
830
Oh, right - thanks Alamout and sid0. And it'd never occurred to me that I could use parameter defaults in a lambda - thanks.

The lambda list comprehension was just in some simple benchmarking tests - nothing directly related to my project. The list of functions is handed to a benchmark function that shouldn't need to be aware of arguments for the subjects so it can just run f() reps*sets times and time it for each function.

sid0":270jm90n said:
Every programmer has hit this at some point in their lives. Consider it a rite of passage.
Thanks. I am learning:
Ps = [] # keep P's so their ids remain unique
class P:
def __init__(self):
Ps.append(self)

def f(p):
print 'f', id(p)
def g(p):
print 'g', id(p)
def h(p):
print 'h', id(p)

#eval func too late:
funcs = [lambda: i(P()) for i in (f, g, h)]

for func in funcs:
func()
func()

print

# eval args too early:
from functools import partial
funcs2 = [partial(i, P()) for i in (f,g,h)]
for func in funcs2:
func()
func()

print

# ah, just right:
funcs3 = [lambda i=i: i(P()) for i in (f,g,h)]

for func in funcs3:
func()
func()
Sometimes it helps just having a greater awareness about certain things that you supposedly do already know.
 

ahankinson

Wise, Aged Ars Veteran
117
Good golly -- that *almost* looks like Python! :)

I still find it kind of weird to be modifying something in the global scope from within a class ("Ps"). Seems to me that could lead to something nasty, but whatever. If you want to work with types, though, you should make sure you always subclass your base classes from "object", a la
Code:
class P(object):
.

http://docs.python.org/2/reference/data ... ic-classes
 

DavlinLotze

Ars Scholae Palatinae
830
Yeah, yeah - I know about old (aka "classic") vs. new style classes. As for inheriting from "object", that's the default with my module, but I can use "" to get an old-style base class. But that bit of code was just a playground example to make sure I had it right - not a part of my project or of the benchmark tests. P and Ps existed only to have distinct trackable objects. (Since each P instance was not otherwise assigned to a lasting variable, I wouldn't have been able to tell from print id(p) if I had the same or a new object. The id's would have been the same or different at the whim of the GC and allocating systems.) As for Ps being in the global scope - sure, I could have defined it under P, but I've been told to avoid class variables, and in defining it there, I'd have had to prefix it with "P." when I used it in __init__.

In the benchmarking tests, I did learn some things. Like that if you're doing a dict lookup where the keys are compared by id(), if there's greater than 1:132 chance (roughly) that the key doesn't exist in the dict, it's faster to say
Code:
if key in mydict: use(mydict[key])
else: do_something_about(key, mydict)
instead of
Code:
try: use(mydict[key])
except KeyError: do_something_about(key, mydict)
In other words, the "if key in mydict:" does take slightly longer than the "try:", but the "except" clause will nail you if it has to be used. (This is for dicts up to about 2**16 members - not sure how it might vary with very large dicts. (Of course if 'mydict' is written to by other threads, you'd need a thread-safe approach.)

It's also slightly faster to use:
Code:
r = mydict[key] = Something()
return r
rather than
Code:
mydict[key] = Something()
return mydict[key]
That second part was what lead to me doing any benchmarking in the first place - not that it matters. I think I was just wanting to escape from my project for a bit. I've run into a recursion bug that's probably something simple I overlooked, but it results in endless recursion (that is, endless until the recursion limit) between 3 functions, but with different values, so the repeat cycle is six function calls long. I'll have to remind myself how the functions were supposed to work in the first place before I can figure it out. But I'll have to look at that later - other fires to put out right now.
 
Status
Not open for further replies.