Redo: How to create a function dynamically.

Peter Otten __peter__ at web.de
Wed Aug 22 21:36:04 CEST 2007


Steven W. Orr wrote:

> I have this which works:
> 
> #! /usr/bin/python
> strfunc = """
> def foo( a ):
>      print 'a = ', a
> """
> exec strfunc
> globals()['foo'] = foo
> foo( 'Hello' )
> 
> and this which does not:
> 
> #! /usr/bin/python
> import new
> strfunc = """
> def foo( a ):
>      print 'a = ', a
> """
> co = compile ( strfunc, '', 'exec' )
> exec co
> nfunc = new.function( co, globals(), 'foo' )
> globals()['foo'] = nfunc
> foo( 'Hello' )
> 
> When I try to run this one I get:
> Traceback (most recent call last):
>    File "./m2.py", line 13, in ?
>      foo( 'Hello' )
> TypeError: ?() takes no arguments (1 given)
> 
> 
> I need the second case to work because I want to be able to end up with a
> function in a seperate module to do the work of function creation. The
> caller will pass in globals() so that the resulting function will end up
> in the directory?/dictionary? of that caller.

'co' is the code that creates the function foo(), not the code that is
executed when foo() is invoked.
Here's the brute force fix to make your script run without error:

#! /usr/bin/python
import new
strfunc = """
def foo( a ):
     print 'a = ', a
"""
co = compile ( strfunc, '', 'exec' )
ns = {}
exec co in ns
nfunc = new.function(ns["foo"].func_code, globals(), 'foo' )
globals()['foo'] = nfunc
foo( 'Hello' )
 
I still don't understand what you're trying to do...

I'm in a nitpicky mood, so
(1) No need to create a new thread for this post.
(2)
http://www.googlefight.com/index.php?lang=en_GB&word1=seperate&word2=separate

Peter





More information about the Python-list mailing list