if <assignment>:

Bengt Richter bokr at oz.net
Sun Nov 24 17:25:00 EST 2002


On Sun, 24 Nov 2002 13:52:12 -0800, Erik Max Francis <max at alcyone.com> wrote:

>André Næss wrote:
>
>> if myvar = someFunction():
>> 
>> My question is, what is the rationale for this? Is it a technical
>> issue? Or
>> purely a matter of language design? I'm curious because I'm interested
>> in
>> the design og programming languages, not because I want this behavior
>> changed in Pyton :)
>
>It's a language design feature, intended to avoid the confusion between
>when people write (say, in C):
>
>	if (a = b) ...
>
>but mean
>
>	if (a == b) ...
>
>Instead in Python assignments are treated as statements, not
>expressions, so they cannot appear in an if clause.
>
except in perverse ways (and this is not the only one):

 >>> a
 Traceback (most recent call last):
   File "<stdin>", line 1, in ?
 NameError: name 'a' is not defined
 >>> b=123
 >>> if [a for a in [b]][0] == 123: print 'aha'
 ...
 aha
 >>> a
 123

BTW, are list comprehensions going to get their own local namespace sometime
or is this the way it's going to be forever?

Regards,
Bengt Richter



More information about the Python-list mailing list