Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > how to dynamically create a function object (from a code object)?

Thread Tools

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

Petri Savolainen
Posts: n/a
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-
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')


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



Reply With Quote

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off

Similar Threads
Thread Thread Starter Forum Replies Last Post
Re: How include a large array? Edward A. Falk C Programming 1 04-04-2013 08:07 PM
Creating object in function doesn't seem to create a new object. Paul Childs Python 1 06-03-2008 08:20 PM
ASP.NET 2.0 - Dynamically create ActiveX object using HtmlGenericControl and call methods / functions all from code behind ASP .Net 4 11-04-2005 04:47 PM
Object creation - Do we really need to create a parent for a derieved object - can't the base object just point to an already created base object jon wayne C++ 9 09-22-2005 02:06 AM
Load User Control Dynamically, Cast object dynamically =?Utf-8?B?UmV6YSBOYWJp?= ASP .Net 1 03-05-2005 12:04 AM