Why I wish Python had assignment in conditionalsThere'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:
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 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 |
These are my WanderingThoughts GettingAround This is part of CSpace, and is written by ChrisSiebenmann. * * * Atom feeds are available; see the bottom of most pages. Categories: links, linux, programming, python, snark, solaris, spam, sysadmin, tech, unix, web |