how to make a code object a function

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Diez B. Roggisch

    how to make a code object a function

    Hi,

    I've got code objects that are created from strings at runtime that look
    like this:

    def p_op1(_, args):
    _.add_dependenc y('p_op1')

    As you migth guess, p_op1 is supposed to become an instance method. Now how
    do I make this code object a function-object that can be set into the
    instances __dict__ to make it a callable method?

    Thanks for any advice,

    Diez B. Roggisch
  • Peter Otten

    #2
    Re: how to make a code object a function

    Diez B. Roggisch wrote:
    [color=blue]
    > Hi,
    >
    > I've got code objects that are created from strings at runtime that look
    > like this:
    >
    > def p_op1(_, args):
    > _.add_dependenc y('p_op1')
    >
    > As you migth guess, p_op1 is supposed to become an instance method. Now
    > how do I make this code object a function-object that can be set into the
    > instances __dict__ to make it a callable method?[/color]

    Too lazy to type self?
    [color=blue][color=green][color=darkred]
    >>> import types
    >>> class T(object):[/color][/color][/color]
    .... def add_dependency( self, name):
    .... print "adding dependency", name
    ....[color=blue][color=green][color=darkred]
    >>> t = T()
    >>> def p_op1(_, args):[/color][/color][/color]
    .... _.add_dependenc y("p_op1")
    ....[color=blue][color=green][color=darkred]
    >>> t.p_op1 = types.MethodTyp e(p_op1, t)
    >>> t.p_op1(1)[/color][/color][/color]
    adding dependency p_op1[color=blue][color=green][color=darkred]
    >>>[/color][/color][/color]

    By the way, types.MethodTyp e and new.instancemet hod seem to be equivalent.

    Peter

    Comment

    • Diez B. Roggisch

      #3
      Re: how to make a code object a function

      Hi,
      [color=blue]
      > Too lazy to type self?[/color]

      yes. I used an underscore in java as indication for member-variables, so
      typing _. appeared natural to me.
      [color=blue][color=green][color=darkred]
      >>>> import types
      >>>> class T(object):[/color][/color]
      > ... def add_dependency( self, name):
      > ... print "adding dependency", name
      > ...[color=green][color=darkred]
      >>>> t = T()
      >>>> def p_op1(_, args):[/color][/color]
      > ... _.add_dependenc y("p_op1")
      > ...[color=green][color=darkred]
      >>>> t.p_op1 = types.MethodTyp e(p_op1, t)
      >>>> t.p_op1(1)[/color][/color]
      > adding dependency p_op1[color=green][color=darkred]
      >>>>[/color][/color]
      >
      > By the way, types.MethodTyp e and new.instancemet hod seem to be equivalent.[/color]

      Interesting - from the docs, I can't see that types.MethodTyp e has a
      constructor like this.

      Your example above gave me the idea to simply exec() my code-object, so in
      the end I have a new function called p_op1 in my scope - that function I
      can get using locals()['p_op1']. I know the name, so that works.

      Just out of curiosity - is there a way to know the name of a code object you
      know nothing about except that it will become a function definition? I
      guess I could go for some AST-stuff looking for a "def foo" statement, so I
      know I will end up having defined foo when exec'ing the code object.

      Regards,

      Diez B. Roggisch

      Comment

      • Emile van Sebille

        #4
        Re: how to make a code object a function

        Diez B. Roggisch:[color=blue]
        > Just out of curiosity - is there a way to know the name of a code[/color]
        object you[color=blue]
        > know nothing about except that it will become a function definition?[/color]
        I[color=blue]
        > guess I could go for some AST-stuff looking for a "def foo"[/color]
        statement, so I[color=blue]
        > know I will end up having defined foo when exec'ing the code object.
        >[/color]

        I'm not quit sure what you're asking, but does sets help?
        [color=blue][color=green][color=darkred]
        >>> ns = locals().keys()
        >>> testing = 1
        >>> print sets.Set(locals ().keys()) - sets.Set(ns)[/color][/color][/color]
        Set(['testing'])


        Emile van Sebille
        emile@fenx.com

        Comment

        • Peter Otten

          #5
          Re: how to make a code object a function

          Diez B. Roggisch wrote:
          [color=blue]
          > Interesting - from the docs, I can't see that types.MethodTyp e has a
          > constructor like this.[/color]

          It get's really funny if you look into the source (types.py):

          class _C:
          def _m(self): pass
          ClassType = type(_C)
          UnboundMethodTy pe = type(_C._m) # Same as MethodType
          _x = _C()
          InstanceType = type(_x)
          MethodType = type(_x._m)

          Seems we caught them cheating here :-)
          [color=blue]
          > Just out of curiosity - is there a way to know the name of a code object
          > you know nothing about except that it will become a function definition? I
          > guess I could go for some AST-stuff looking for a "def foo" statement, so
          > I know I will end up having defined foo when exec'ing the code object.[/color]

          You could provide a separate namespace and then extract only the callables:
          [color=blue][color=green][color=darkred]
          >>> d = {}
          >>> exec "factor=2\n def alpha(s, t): print factor*t" in d
          >>> d.keys()[/color][/color][/color]
          ['__builtins__', 'alpha', 'factor'][color=blue][color=green][color=darkred]
          >>> funcs = dict([(n,f) for n, f in d.iteritems() if callable(f)])
          >>> funcs[/color][/color][/color]
          {'alpha': <function alpha at 0x4029025c>}[color=blue][color=green][color=darkred]
          >>> funcs["alpha"](None, 2)[/color][/color][/color]
          4

          Peter


          Comment

          • Diez B. Roggisch

            #6
            Re: how to make a code object a function

            > You could provide a separate namespace and then extract only the[color=blue]
            > callables:
            >[color=green][color=darkred]
            >>>> d = {}
            >>>> exec "factor=2\n def alpha(s, t): print factor*t" in d
            >>>> d.keys()[/color][/color]
            > ['__builtins__', 'alpha', 'factor'][color=green][color=darkred]
            >>>> funcs = dict([(n,f) for n, f in d.iteritems() if callable(f)])
            >>>> funcs[/color][/color]
            > {'alpha': <function alpha at 0x4029025c>}[color=green][color=darkred]
            >>>> funcs["alpha"](None, 2)[/color][/color]
            > 4[/color]

            And again I learned something completely new - cool. Thanks,

            Diez

            Comment

            Working...