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

  • Thread starter Petri Savolainen
  • Start date
P

Petri Savolainen

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):

Traceback (most recent call last):
File "<pyshell#136>", line 1, in -toplevel-
f('hello')
TypeError: ?() takes no arguments (1 given)

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
>>> 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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,266
Messages
2,571,082
Members
48,773
Latest member
Kaybee

Latest Threads

Top