setattr() oddness

Steve Holden steve at holdenweb.com
Fri Jan 15 18:09:01 EST 2010


Terry Reedy 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.
> 
Good question, great answer!

regards
 Steve
-- 
Steve Holden           +1 571 484 6266   +1 800 494 3119
PyCon is coming! Atlanta, Feb 2010  http://us.pycon.org/
Holden Web LLC                 http://www.holdenweb.com/
UPCOMING EVENTS:        http://holdenweb.eventbrite.com/




More information about the Python-list mailing list