[Python-ideas] Anaphoric if

Andrey Fedorov anfedorov at gmail.com
Sat Apr 24 20:05:03 CEST 2010


On Sat, Apr 24, 2010 at 1:13 PM, Ron Adam <rrr at ronadam.com> wrote:

>  On 04/23/2010 07:23 PM, Jess Austin wrote:
>
> > for the sake of completeness: would the following:
> >
> > if not foo() as x:
> >      ... x
> >
> > mean this:
> >
> > x = foo()
> > if not x:
> >      ... x
>
>
> I would think it would defined as
>
>     if expression as name:
>         block using name
>
> Which would be...
>
>    x = not foo()
>    if x:
>        ... x
>
> So it could be tricky to get the correct behavior unless (expression as
> name) becomes a valid expression in it self, but then it wouldn't be limited
> to the if block, so you might as well just use (expression = name).
>

Err, that is *not* "correct behavior". This is the third time I'm repeating
myself (not including the subject): I'm talking about an *anaphoric if*.
That is an if statement which can refer back to its predicate, nothing
more.

Another issue would be, what if x already existed? would it just write over
> it, or raise a NameError. If it wrote over it, would it be restored after
> the block to it's previous value? All of this adds unneeded complexity to
> the language without adding any real benefits.


No extra complexity: make it identical to the expanded version. That also
makes it identical to how the "local" variable in [x for x in ...] behaves,
which is expected.

Yes it reduces the line count by one, but what meaningful use case is
> enabled with this that we can't already do?


The benefit isn't the line, it's the aesthetic of a direct transcription of
your intentions:

x = foo()

should be reserved for x having meaning in the local scope. Think of it this
way: is it more natural to say "if you have kids, register them for swimming
lessons", or "consider your kids. if there are any kids, register them for
swimming lessons".

- Andrey
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20100424/c76e6017/attachment.html>


More information about the Python-ideas mailing list