[Python-ideas] Combining test and assignment

Jakob Bowyer jkbbwr at gmail.com
Sun Jan 22 00:30:49 CET 2012


Say I have a function that is
def test():
    return sometimes_false

if test() as x:
    print "Its not false"
# what happens to x now? is it a NameError or is it None

On Sat, Jan 21, 2012 at 10:23 PM, Eike Hein <sho at eikehein.com> wrote:

>
> 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
> ______________________________**_________________
> Python-ideas mailing list
> Python-ideas at python.org
> http://mail.python.org/**mailman/listinfo/python-ideas<http://mail.python.org/mailman/listinfo/python-ideas>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20120121/ec096d7a/attachment.html>


More information about the Python-ideas mailing list