setattr() oddness

Sean DiZazzo half.italian at gmail.com
Fri Jan 15 18:10:33 EST 2010


On Jan 15, 2:22 pm, Terry Reedy <tjre... at udel.edu> 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.

Thanks for the info!

~Sean



More information about the Python-list mailing list