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

Cem Karan cfkaran2 at gmail.com
Fri Dec 19 11:57:43 CET 2014

On Dec 19, 2014, at 12:15 AM, Chris Angelico <rosuav at gmail.com> wrote:

> On Fri, Dec 19, 2014 at 3:27 PM, Cem Karan <cfkaran2 at gmail.com> wrote:
>> I'd like to suggest that getattr(), setattr(), and hasattr() all be modified so that syntactically invalid statements raise SyntaxErrors.
> Is there actually a need to have them check like that? :) After all,
> attributes are just stored in a dictionary. You want
> syntactically-invalid attributes? Sure, no problem.

Its only needed from a 'Principle of Least Astonishment' point of view.  When I realized I could work my way around the syntax by using getattr()/setattr(), I was astonished.  I really didn't expect it to work, and I would MUCH prefer that trying to use getattr()/setattr() in this way would have the exact same results as normal attribute access.

>> 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.
> Syntax comes first. If you want to play with redefinitions like that,
> it'd be simpler to stuff stuff into globals(), which is also simply a
> dictionary.
>>>> globals()["3"]=4
>>>> 3
> 3
>>>> globals()["3"]
> 4
> When you type 3, Python compiles that into the integer 3, not into a
> name lookup. Now, you *can* fiddle with this kind of thing using
> ctypes, though I don't know how many other interpreters (PyPy, Jython,
> etc) will let you shoot yourself in that particular foot. But if you'd
> like to play around with this kind of thing, check out the 'ast'
> module and try compiling code to AST, then fiddling with it a bit,
> then finishing compilation and execution. And python-list will
> probably enjoy discussing the random things you can accomplish with
> that :) It's good fun.

I feel a wave of morbid curiosity coming over me... I think I'm going to have to try that, just to see what I can do.  I'm terrified to think that I might actually be able to make it happen... O_o.  

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?

Cem Karan

More information about the Python-ideas mailing list