[Python-ideas] Bug? Feature? setattr(foo, '3', 4) works!

Nick Coghlan 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:

>>> x.a
1
>>> getattr(x, 'a')
1
>>> x.__dict__['a']
1

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
object.

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')
2
>>> x.__dict__['not a legal identifier']
2

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.

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20141219/e8d9eea2/attachment-0001.html>


More information about the Python-ideas mailing list