[Python-Dev] New syntax for 'dynamic' attribute access

Georg Brandl g.brandl at gmx.net
Tue Feb 13 09:33:49 CET 2007


Martin v. Löwis schrieb:
> Ron Adam schrieb:
>> I think it's gets a bit awkward in some situations.
>> 
>> 
>>     if bar->'__%s__' % attr < -42: print 'Hello World'
>> 
>>     if bar.['__%s__' % attr] > -42: print 'Hello World'
>> 
>> 
>> To me it's easier to parse the second one visually.
> 
> 
> Ah, precedence.
> 
> It definitly should be a bracketed form, or else people
> always wonder what the precedence is, and add parenthesis
> anyway just to be on the safe side.

Indeed.

> BTW, which of these would be correct
> 
>   (a).[b]
Yes. (you can write (a).b today)

>   (a.)[b]
No. (you can't write (a.)b today)

>   a.[(b)]
Yes. (you can write a[(b)] today)

>   a.([b])
No. (you can't write a([b]) today)

>   a   .  [  b  ]
Yes. (you can write a . b today)

In short, I'd just add a new form to Grammar's trailer:

trailer: '(' [arglist] ')' | '[' subscriptlist ']' | '.' attrtrailer
attrtrailer: '[' test ']' | NAME

This should be consistent and unsurprising.

> and what is the semantics of
> 
>   a.[42]

A TypeError, just as getattr(a, 42) would be.

I think I like the .[] form better, that being a +0 now.

Georg



More information about the Python-Dev mailing list