Creating function object from text

E

Edward C. Jones

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

Peter Hansen

Edward said:
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?

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
 
G

George Yoshida

Edward said:
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?

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

Michel Claveau/Hamster

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 !
 

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

Forum statistics

Threads
474,184
Messages
2,570,979
Members
47,578
Latest member
LC_06

Latest Threads

Top