[SPAM] Re: "as" keyword woes

MRAB google at mrabarnett.plus.com
Thu Dec 4 00:17:46 CET 2008


Albert Hopkins wrote:
> On Wed, 2008-12-03 at 13:38 -0800, Warren DeLano wrote:
>> A bottom line / pragmatic question... hopefully not a FAQ.
>>
>> Why was it necessary to make "as" a reserved keyword?  
>>
>> And more to the point, why was it necessary to prevent developers from
>> being able to refer to attributes named "as"?  
>>
>> For example, this code breaks as of 2.6 / 3.0:
>>
>> Class C:
>>     Pass
>>
>> obj = C()
>>
>> obj.bs = 2 # valid
>>
>> obj.as = 1 # syntax error
>>
>> obj.cs = 3 # valid
>>
>> Just to be clear:  I understand why it breaks, since "as" is now a
>> keyword, I also know that one can use workarounds such as:
>>
>> obj.__dict__['as'] = 1
>>
>> to maintain compatibility.
>>
>> What I want to understand is why this parser change was necessary in
>> order to enable new 2.6/3.0 features.  Was this change potentially
>> avoidable?
>>
>> Why can't the parser distinguish between a standalone " as " keyword and
>> ".as" used as an object/attribute reference?
>>
>> Couldn't we have continued along just fine using a smarter parser
>> without elevating "as" to reserved status (and thus potentially breaking
>> a 10+ years of existing code)?
>>
>> Thank you for enlighting me!
>>
>> (Unfortunately, our project may now have to maintain a branch at 2.5.x
>> in order to preserve compatibility with existing third-party scripts &
>> infrastructure which routinely rely upon "as" as an object method.
>> Sigh.)
>>
>> Cheers,
>> Warren
> 
> The short answer is that "as" is a keyword as of 2.6 (with the
> introduction of the "with" statement) and to be fair none of the other
> keywords can be identifiers.
> 
> Also to be fair, there seems to be warning at least in my version of
> python 2.5:
> 
>>>> import sys
>>>> sys.version_info
> (2, 5, 1, 'final', 0)
>>>> class C:
> ...     pass
> ... 
>>>> obj = C()
>>>> obj.as = 3
> <stdin>:1: Warning: 'as' will become a reserved keyword in Python 2.6
> 
The parser in Python v2.5 can identify when "as" has its special meaning 
by context, but it's better to be consistent. Hopefully there won't be 
many reserved words (IIRC, COBOL has a _large_ number of them)! If you 
still want a name like that then the convention is to add a trailing 
underscore, eg the "pass_" method of POP3 objects in poplib. That 
probably doesn't help you, though. :-(



More information about the Python-list mailing list