On Tue, 03 Apr 2007 05:08:42 +0100, Paulo da Silva wrote:

> Hi!
> 
> In a class C, I may do setattr(C,'x',10).
> 
> Is it possible to use getattr/setattr for variables not inside
> classes or something equivalent? I mean with the same result as
> exec("x=10").

Yes, but you shouldn't unless you really need to. You're better off
rethinking your algorithm.

If you think you really need to, you probably don't.

If you *really* think you really need to, you might.


>>> x
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
NameError: name 'x' is not defined
>>> globals()['x'] = 5
>>> x
5


Note that there is also a function locals(), but it doesn't work as you
might expect:


>>> def f():
...     locals()['x'] = 99
...     print x
...
>>> f()
5



-- 
Steven D'Aprano 

-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to