setattr() oddness

Terry Reedy tjreedy at
Sat Jan 16 03:12:19 CET 2010

On 1/15/2010 6:10 PM, Sean DiZazzo wrote:
> On Jan 15, 2:22 pm, Terry Reedy<tjre... at>  wrote:
>> On 1/15/2010 3:37 PM, Sean DiZazzo wrote:
>>> Should the following be legal?
>>>>>> class TEST(object): pass
>>> ...
>>>>>> t = TEST()
>>>>>> setattr(t, "", "123")
>>>>>> getattr(t, "")
>>> '123'
>> Different people have different opinions as to whether setattr (and
>> correspondingly getattr) should be strict or permissive as to whether or
>> not the 'name' string is a legal name. CPython is permissive. The
>> rationale is that checking would take time and prevent possible
>> legitimate use cases.
>> CPython is actually looser than this. Try
>> t.__dict__[1] = 2
>> Now there is an 'attribute' whose 'name' is an int! -- and which can
>> only be accessed via the same trick of delving into the internals. This
>> is, however, implementation behavior that would go away if an
>> implementation used string-key-only dicts to store attributes.
>> Terry Jan Reedy
> Interesting.  I can understand the "would take time" argument, but I
> don't see any legitimate use case for an attribute only accessible via
> getattr().  Well, at least not a pythonic use case.

That was my first thought, but one thing I thought of would be a proxy 
object for remote objects coded in a language with different name rules, 
or any situation where 'names' and values come over the wire to be 
stored and later retrieved, so that all 'foreign' attribute access was 
done with set/get/del/attr.

I expect that creative Python programmers have found other uses too.

Terry Jan Reedy

More information about the Python-list mailing list