how to dynamically create a function object (from a code object)?

anton muhin antonmuhin.REMOVE.ME.FOR.REAL.MAIL at rambler.ru
Wed Jul 2 07:37:33 EDT 2003


Petri Savolainen wrote:
> After reading the manuals and googling around a bit, I thought I'd use 
> the 'compile' built-in to create a code object. Then, using either 
> new.function() or types.FunctionType(), create a function object out of 
> the code object. The function object can then be turned into a method 
> for example using types.MethodType(). Right? Well, on Windows 98, using 
> python 2.2.2 (or 2.3b2):
> 
>  >>> c=compile('def a(msg): return msg','<nowhere>','exec')
>  >>> f=types.FunctionType(c,globals(),'a')
>  >>> f
>  >>> <code object ? at 00F8A9E0, file "<nowhere>", line 1>
>  >>> f('hello')
> 
> Traceback (most recent call last):
>   File "<pyshell#136>", line 1, in -toplevel-
>     f('hello')
> TypeError: ?() takes no arguments (1 given)
> 
>  >>> f()
>  >>>
>  >>> a('hello')
>  >>> 'hello'
>  >>>
> 
> This is, well, not what I would have expected.
> 
> After peeking around in the code object, I found out its 'co_const' 
> instance variable also contains a code object - which, it seems, should 
> really be fed to the function creation methods:
> 
>  >>> c.co_consts
> (<code object a at 00F8A960, file "<nowhere>", line 1>, None)
>  >>> f=types.FunctionType(c.co_consts[0],globals(),'a')
>  >>> f('hello')
> 'hello'
>  >>>
> 
> Which is the behaviour I would have expected in the first place!
> 
> I would really like to know what I am doing wrong here, or any 
> clarification regarding what is going on above... I dare not hope having 
> found a bug :-P
> 
> Thanks,
> 
>  Petri
> 

Unfortunately, I didn't manage to do it the way you described above. But 
if you just want to create a function there is much simplier way:

def create_id():
	def _(s): return s
	return _

x = _()
x("xxx")

hth,
anton





More information about the Python-list mailing list