dynamic construction of variables / function names

Felipe Almeida Lessa felipe.lessa at gmail.com
Thu Mar 30 09:08:13 CEST 2006


Em Qua, 2006-03-29 às 22:44 -0800, Sakcee escreveu:
> either eval or exec should be used
> is it correct way, is there a simple way, is this techniqe has a name?

eval and exec are insecure. Try looking at globals():

$ python2.4
Python 2.4.3c1 (#2, Mar 29 2006, 08:34:35)
[GCC 4.0.3 (Debian 4.0.3-1)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> def Newfoo(a, b):
...     return a+b
...
>>> def Newblah(c, d):
...     return c*d
...
>>> list = ["foo", "blah"]
>>> for func in list:
...     print globals()["New"+func](2, 4)
...
6
8
>>> # That was a bit confusing, let see in parts
... print globals()
{'Newblah': <function Newblah at 0xb7d3df44>,
 '__builtins__': <module '__builtin__' (built-in)>,
 'Newfoo': <function Newfoo at 0xb7d3df0c>,
 'list': ['foo', 'blah'],
 'func': 'blah',
 '__name__': '__main__',
 '__doc__': None}
>>> print globals()["New"+func]
<function Newblah at 0xb7d3df44>
>>> print globals()["New"+func](2, 4)
8
>>> # HTH,
...

-- 
Felipe.




More information about the Python-list mailing list