Bug? Feature? setattr(foo, '3', 4) works!

Dave Angel davea at davea.name
Fri Dec 19 08:22:00 EST 2014


On 12/19/2014 06:40 AM, Cem Karan wrote:
> I'm bringing this discussion over from the python-ideas mailing list to see what people think. I accidentally discovered that the following works, at least in Python 3.4.2:
>
>>>> class foo(object):
> ...     pass
> ...
>>>> setattr(foo, '3', 4)
>>>> dir(foo)
> ['3', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__']
>>>> getattr(foo, '3')

<snip>
>
> However, the following doesn't work:
>
>>>> foo.3
>   File "<stdin>", line 1
>     foo.3
>         ^
> SyntaxError: invalid syntax
>>>> bar.3
>   File "<stdin>", line 1
>     bar.3
>         ^
> SyntaxError: invalid syntax
>
> I'd like to suggest that getattr(), setattr(), and hasattr() all be modified so that syntactically invalid statements raise SyntaxErrors. In messages on python-ideas, Nick Coghlan mentioned that since a Namespace is just a dictionary, the normal error raised would be TypeError and not SyntaxError; I'd like to suggest special-casing this so that using getattr(), setattr(), and hasattr() in this way raise SyntaxError instead as I think that will be less astonishing.
>

They are NOT syntactically invalid, but perhaps you mean they should be 
considered semantically invalid.  That's a very important distinction.

Suppose for example the function call is
     setattr(foo, name, value)

If the setattr() call is made inside a function, there's no way that the 
compiler could detect it as a syntax error.  IF YOU decide it should be 
a runtime error, then labelling it as a syntax error would be very 
confusing to anyone who understands the compile process.

I personally don't think it should be an error at all, and that current 
behavior is just fine.

-- 
DaveA



More information about the Python-list mailing list