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') 4 bar = foo() dir(bar) ['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(bar, '3') 4 hasattr(foo, '3') True hasattr(bar, '3') True
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. On a related note, are numbers defined in a module, or they are part of interpreter? Just to see how awful I could make things, I tried to extend the above to redefine 3 to be 4. Fortunately (unfortunately?) I couldn't find a way, but I'm curious if there is a pythonic way of making this happen, and if there is, I'd like to suggest making that impossible ASAP. Thanks, Cem Karan