use of exec()

lars van gemerden lars at rational-it.com
Thu Oct 18 10:07:30 EDT 2012


On Thursday, October 18, 2012 1:49:35 PM UTC+2, Chris Angelico wrote:
> 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

Thanks, Chris,

That works like a charm (after replacig "return ns.function" with "return ns['function']" ;-) ).

About the security, i noticed you can still import and use modules within the exec'ed code. Is there a way to prevent this or otherwise make this approach more secure.

I should say that the users that will be able to make custom functions, are not end-users, but authenticated designers, however i would like to close a backdoor to the whole framework.

Cheers, Lars 






More information about the Python-list mailing list