setattr using invalid attribute names - bug or feature?

G

Gerson Kurz

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

(oh, and its: PythonWin 2.3.3 (#51, Dec 18 2003, 20:22:39) [MSC v.1200
32 bit (Intel)] on win32.)
 
P

Peter Hansen

Gerson said:
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?

Okay. But so what?

-Peter
 
Y

Yermat

Peter said:
Okay. But so what?

-Peter

And sometime it is usefull to create some attributes that can unlikely
be used by the programmer (for example for cache or...).

I've seen code on coockbook that were using that property.
 
M

Meno

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:
123

Meno.
 
L

Larry Bates

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top