Creating function object from text

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Edward C. Jones

    Creating function object from text

    Suppose I have a piece of text that defines a function:

    text ="""\
    def fun(i):
    return i + 2
    """

    How do I turn this into a function object, f, which can be called or
    passed around?
  • Peter Hansen

    #2
    Re: Creating function object from text

    Edward C. Jones wrote:
    [color=blue]
    > Suppose I have a piece of text that defines a function:
    >
    > text ="""\
    > def fun(i):
    > return i + 2
    > """
    >
    > How do I turn this into a function object, f, which can be called or
    > passed around?[/color]

    exec text

    If you need to do this other than in the global namespace of the
    module, read up on the exec statement and how you can pass in a
    dictionary of your own.

    -Peter

    Comment

    • George Yoshida

      #3
      Re: Creating function object from text

      Edward C. Jones wrote:
      [color=blue]
      > Suppose I have a piece of text that defines a function:
      >
      > text ="""\
      > def fun(i):
      > return i + 2
      > """
      >
      > How do I turn this into a function object, f, which can be called or
      > passed around?[/color]

      Aside from Peter's advice, I'd recommend you to look into timeit.py and
      doctest.py.
      These two library is a good example of how to use exec and compile in a
      real application.

      --
      George

      Comment

      • Michel Claveau/Hamster

        #4
        Re: Creating function object from text

        Bonjour !

        Ce code fonctionne, chez moi :

        src='''def toto(i):
        return i*2'''

        exec src
        print toto(3) # => 6



        Mais, dans certains cas, je suis obligé d'ajouter :
        global toto



        Bonne soirée !

        --
        Michel Claveau


        Comment

        Working...