use of exec()
Chris Angelico
rosuav at gmail.com
Thu Oct 18 07:49:31 EDT 2012
On Thu, Oct 18, 2012 at 10:41 PM, lars van gemerden
<lars at rational-it.com> wrote:
> NameError: name 'function' is not defined
>
> which seems an odd error, but i think some global variable is necessary for this to work (if i put in globals() instead of {}, it works).
The def statement simply adds a name to the current namespace. This
should work (untested):
class _functioncode(code):
def _creat_func_(self):
ns={}
exec("def function(%s):\n\t%s" % (", ".join(type(self).args),
"\n\t".join(self.split('\n'))),ns,ns)
return ns.function
But it's going to be eternally plagued by security issues. You may
want, instead, to look at literal_eval from the ast module; but that
won't work if you need anything other than, as the name suggests,
literals.
ChrisA
More information about the Python-list
mailing list