setattr using invalid attribute names - bug or feature?

Larry Bates lbates at swamisoft.com
Mon Jun 14 15:55:46 EDT 2004


You can also do this:

class test:
    pass


instance = test()
setattr(instance, "THIS :*2+~# IS OBVIOUSLY INVALID", 123)

>>> print instance.__dict__["THIS :*2+~# IS OBVIOUSLY INVALID"]
>>> 123

>>> print instance.__dict__.keys()
>>> ['THIS :*2+~# IS OBVIOUSLY INVALID']

>>> print instance.__dict__.items()
>>> [('THIS :*2+~# IS OBVIOUSLY INVALID', 123)]

The only reason that you cannot do:

instance.This :*2+~# IS OBVIOUSLY INVALID

is because attribute names accessed in this
fashion can't have spaces.

Larry Bates,
Syscon, Inc.

"Meno" <dontaskme at doityourself.com> wrote in message
news:9c2d8268.0406141002.5c1d1e6 at posting.google.com...
> gerson.kurz at t-online.de (Gerson Kurz) wrote in message
news:<40cdb3d5.2146906 at news.t-online.de>...
> > I stumbled across this (while using my homebrewn enum class):
> >
> >     class test:
> >         pass
> >
> >     instance = test()
> >     setattr(instance, "THIS :*2+~# IS OBVIOUSLY INVALID", 123)
> >
> > I would've expected some kind of error message here when calling
> > setattr(); after all, its not a regular attribute? Plus, documentation
> > says
> >
> > "
> >  Set a named attribute on an object; setattr(x, 'y', v) is equivalent
> > to
> >     ``x.y = v''.
> > "
> >
> > and you cannot write this:
> >
> > instance.THIS :*2+~# IS OBVIOUSLY INVALID = 123
>
> No, but you can write this:
>
> >>> a = getattr(instance, "THIS :*2+~# IS OBVIOUSLY INVALID")
> >>> print a
> 123
>
> Meno.





More information about the Python-list mailing list