[Python-ideas] Bug? Feature? setattr(foo, '3', 4) works!
ncoghlan at gmail.com
Fri Dec 19 14:54:25 CET 2014
On 19 December 2014 at 23:46, Nick Coghlan <ncoghlan at gmail.com> wrote:
> On 19 December 2014 at 21:17, Cem Karan <cfkaran2 at gmail.com> wrote:
>> On Dec 19, 2014, at 6:03 AM, Nick Coghlan <ncoghlan at gmail.com> wrote:
>> > On 19 December 2014 at 20:57, Cem Karan <cfkaran2 at gmail.com> wrote:
>> > But, getting back to the main question, is this a bug or a feature? I
>> personally feel like this is a bug, and I'd like to both clarify it in the
>> language spec, and have cpython modified to enforce the syntax, regardless
>> of how you try to mess with an attribute. How does everyone else feel
>> about this?
>> > Namespaces are just dictionaries. The one thing implementations may do
>> is to place a type restriction on the keys, so they throw TypeError if you
>> try to use something other than str (although *CPython* doesn't do that).
>> > getattr/setattr/delattr would never throw SyntaxError though - that's
>> only thrown by the compiler.
>> I see what you're saying, but I feel like having (get|set|has)attr throw
>> TypeError instead of SyntaxError would itself be astonishing in this case.
>> The feature I'm after is that "foo.3" results in exactly the same behavior
>> as "getattr(foo, '3')".
> I can probably save you some time: not going to happen :)
To elaborate on that a bit:
>>> getattr(x, 'a')
The ".a" attribute access syntax is ultimately just syntactic sugar for a
dictionary lookup with the string 'a'. That syntactic sugar is what applies
the restriction to being a valid identifier, not the underlying namespace
Even for string values, you can do syntactically unacceptable lookups via
the underlying namespace mapping:
>>> setattr(x, 'not a legal identifier', 2)
>>> getattr(x, 'not a legal identifier')
>>> x.__dict__['not a legal identifier']
You'll find that kind of behaviour in a few different areas - syntactic
restrictions aren't actually present in the underlying runtime machinery,
they only exist at compile time.
Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Python-ideas