[Python-ideas] Anaphoric if

John Graham john.a.graham at gmail.com
Sun Apr 25 02:33:51 CEST 2010


not to go too far off on an unrelated tangent here but couldn't your
use case be covered by polymorphism on the return value of foo, one
potential return value representing the if x case while another value
representing the branch if none case. this would be similar to the
'maybe' monad in haskell, 'optional' in the ml languages, or the 'null
object' pattern in OO.  completely representable in python without any
addition to the syntax.

On 4/24/10, Andrey Fedorov <anfedorov at gmail.com> wrote:
> 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
>



More information about the Python-ideas mailing list