how to convert a multiline string to an anonymous function?
Scott David Daniels
Scott.Daniels at Acm.Org
Wed Apr 30 09:00:36 EDT 2008
Matimus wrote:
> On Apr 29, 3:39 pm, "Diez B. Roggisch" <de... at nospam.web.de> wrote:
>> Danny Shevitz schrieb:
>>> Simple question here: ...
>>> str = '''
>>> def f(state):
>>> print state
>>> return True
>>> '''
>>> but return an anonmyous version of it, a la 'return f' so I can assign it
>>> independently. The body is multiline so lambda doesn't work....
>> The "stupid" thing is that you can pass your own dictionary as globals
>> to exec. Then you can get a reference to the function under the name "f"
>> in the globals, and store that under whatever name you need....
>> Diez
> ...
Or, you can even more simply do:
text = '''
def f(state):
print state
return True
'''
lcl = {}
exec text in globals(), lcl
and lcl will be a dictionary with a single item: {'f' : <function>}
so you could return lcl.values()[0]
-Scott David Daniels
Scott.Daniels at Acm.Org
More information about the Python-list
mailing list