Redo: How to create a function dynamically.

Steven W. Orr steveo at syslang.net
Wed Aug 22 15:10:54 EDT 2007


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.

[And my apologies for overcomplicating the question on my first try.]

-- 
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net



More information about the Python-list mailing list