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

Discussion in 'Python' started by Petri Savolainen, Jul 1, 2003.

  1. 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
    Petri Savolainen, Jul 1, 2003
    #1
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. =?Utf-8?B?UmV6YSBOYWJp?=

    Load User Control Dynamically, Cast object dynamically

    =?Utf-8?B?UmV6YSBOYWJp?=, Mar 4, 2005, in forum: ASP .Net
    Replies:
    1
    Views:
    6,702
    Matt Berther
    Mar 5, 2005
  2. =?Utf-8?B?UmV6YSBOYWJp?=

    Load User Control Dynamically, Cast object dynamically

    =?Utf-8?B?UmV6YSBOYWJp?=, Mar 4, 2005, in forum: ASP .Net
    Replies:
    1
    Views:
    6,344
    Scott Allen
    Mar 4, 2005
  3. Replies:
    4
    Views:
    16,197
  4. MRW
    Replies:
    7
    Views:
    453
    Mark Rae
    Aug 6, 2006
  5. Steven W. Orr
    Replies:
    1
    Views:
    260
    Peter Otten
    Aug 22, 2007
Loading...

Share This Page