Wandering Thoughts archives


Why I wish Python had assignment in conditionals

There's a lot of times where a function wants to return more than a plain boolean; for example, validation routines often want to return some sort of explanation of the validation error (if there is one). At the same time, the most natural way to use the function is often in the flow of a conditional:

if blah(o):
elif not validates(o):
    # whoops, lost the error reason

There's a variety of traditional answers to this, but I don't really like any of them because they all obscure (to some degree) the logic of what is going on. The right way of saying 'I am using this as a condition but capturing its return value for later use' is an assignment in a conditional; it is explicit and unambiguous (apart from the bit where = and == are too close to each other).

Python being Python, we can of course actually do this via a suitable hack:

def capture(store, res):
    store[0] = res
    return res

store = [None,]
if blah(o):
elif capture(store, validates(o)):
    ... use store[0] ...

Just like the last one, I suspect that this is not going to be considered really Pythonic.

(With sufficient cleverness, you can construct a version of capture() that is passed store's name and puts the result in it directly, without needing you to make it an array and use store[0]. To appeal to the Lisp crowd, call the routine let().)

python/AssignmentInConditionals written at 22:50:31; Add Comment

Page tools: See As Normal.
Login: Password:
Atom Syndication: Recent Pages, Recent Comments.

This dinky wiki is brought to you by the Insane Hackers Guild, Python sub-branch.