setattr() oddness
Terry Reedy
tjreedy at udel.edu
Fri Jan 15 17:22:42 EST 2010
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
More information about the Python-list
mailing list