[Python-ideas] Combining test and assignment

Eike Hein sho at eikehein.com
Sat Jan 21 23:23:20 CET 2012


Hello,

this is very spur of the moment, and so I apologize if
I am missing the obvious reasons for why this would be
horribly dumb.

I sometimes find myself annoyed that I cannot access the
result of an expression in a conditional statememt.

Consider:

if spam():
    ... frobulate the return value of spam() ...
else:
    ... value too low to frobulate ...

In order to frobulate spam(), either need to call it
again in the indented block, or preassign:

x = spam()

if x:
     ... frobulate x ...

The first option is usually inefficient, and the second
feels ugly to me because something relevant to a block is
happening outside it and its header.

Instead, I'd love to be able to:

if spam() as x:
    ... frobulate x ...

Further, there are two reasons this seems a particularly
good fit in Python:
- There is a _syntactic_ precedent, or at least great
   similarity to the 'with' statement.
- Because calls in Python return None if they don't ex-
   plicitly return anything else, there is no "can't assign
   void to x" to worry about.

I haven't given much thought to scoping, particularly for
else clauses, yet, at least not enough to make up my mind.

The other question is if this reads good "as English" or
needs to be 'if spam() then as x:', or if that's even an
issue.

Thoughts?


Best regards,
Eike



More information about the Python-ideas mailing list