implicit variable declaration and access

Benji York benji at benjiyork.com
Mon Jun 13 13:18:34 EDT 2005


Ali Razavi wrote:
> Ali Razavi wrote:
> 
>>Is there any reflective facility in python
>>that I can use to define a variable with a
>>name stored in another variable ?

> Got it! use higher order functions like Lisp!

No, you use higher order functions like Python.  :)

> code = x + '= 0'
> exec(code)

You should generally stay away from exec for lots of reasons.  I won't 
elaborate but a search of this group would be informative.

If you want to affect the globals (which you probably don't) you can 
do this:

 >>> x = 'my_var'
 >>> globals()[x] = 7
 >>> my_var
7

If you want to set an attribute on a particular object (which is more 
likely), you can do this:

 >>> class C:
...  pass
...
 >>> c = C()
 >>> setattr(c, x, 8)
 >>> c.my_var
8

> code = 'print ' + x
> exec(code)

Getting the value would be like this, respectively:

 >>> print globals()[x]
7
 >>> getattr(c, x)
8

HTH
--
Benji York



More information about the Python-list mailing list