getattr/setattr q.

Steve Holden steve at
Tue Apr 3 18:11:45 CEST 2007

Paulo da Silva wrote:
> Steven Bethard escreveu:
>> Paulo da Silva wrote:
> ...
>> If you're at the module level, you can do::
>>     globals()['x'] = 10
>> If you're inside a function, you probably want to look for another way
>> of doing what you're doing.
>> What's the actual task you're trying to accomplish here?
> None. I asked just for curiosity. My problem has to do with the normal
> case of a class or class instance. When I saw setattr/getattr as the way
> to solve my problem I just felt curiosity on if and how it could be done
> outside a class.
> Thank you very much for your response.
> Paulo

You don't need setattr/getattr if you know in advance the name of the 
attribute you need to access and you can get a reference to the object 
whose attribute it is. So:

  >>> import sys
  >>> x = "Hello, Paulo"
  >>> sys.modules['__main__'].x
'Hello, Paulo'
  >>> globals()['x']
'Hello, Paulo'

Steve Holden       +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd
Skype: holdenweb
Recent Ramblings

More information about the Python-list mailing list