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

Chris Angelico rosuav at gmail.com
Fri Dec 19 12:11:39 CET 2014


On Fri, Dec 19, 2014 at 10:00 PM, Nick Coghlan <ncoghlan at gmail.com> wrote:
> Most implementations will go with whichever is faster in their particular
> case (for CPython, that means using the standard permissive dict type, for
> Jython, it means only allowing strings, for other implementations, I'm not
> sure).

What do you mean by "only allowing strings"? CPython doesn't allow
non-string attributes, and Jython does allow non-identifier
attributes:

Jython 2.5.3 (, Oct 8 2014, 03:39:09)
[OpenJDK 64-Bit Server VM (Oracle Corporation)] on java1.7.0_65
Type "help", "copyright", "credits" or "license" for more information.
>>> class x(object): pass
...
>>> x=x()
>>> setattr(x,"1","2")
>>> getattr(x,"1")
'2'
>>> setattr(x,1,2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: setattr(): attribute name must be string

Python 3.5.0a0 (default:64e45efdc3e2, Dec 11 2014, 11:52:01)
[GCC 4.7.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> class x: pass
...
>>> x=x()
>>> setattr(x,"1",2)
>>> getattr(x,"1")
2
>>> setattr(x,1,2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: attribute name must be string, not 'int'


(I'm not sure why there's the empty string in the Jython version tag;
this is what I got by apt-getting jython on Debian Jessie.)

In any case, it's probably time this moved off python-ideas.

ChrisA


More information about the Python-ideas mailing list