Re: how to convert a multiline string to an anonymous function?



Matimus wrote:
On Apr 29, 3:39 pm, "Diez B. Roggisch" <de...@xxxxxxxxxxxxx> 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@xxxxxxx
.



Relevant Pages

  • Re: Anonymus functions revisited : tuple actions
    ... Checks locals, globals, and builtins for the varable name. ... def isa: ... otherwise return the varable obj. ...
    (comp.lang.python)
  • Re: PEP-343 - Context Managment variant
    ... > def Synhronised: ... 'globals' means the module global namespace as returned by globals. ... We must declare local vars, to which we wish assign in "global" ... You cannot rebind enclosed local variables, ...
    (comp.lang.python)
  • Re: singletons
    ... this is a common approach in python. ... The one drawback to this is that it could require lots of globals ... def something: ...
    (comp.lang.python)
  • Re: undo a dictionary
    ...     for key, value in dd.items: ... globals() as the default names space, ... def undict(self, dict): ...
    (comp.lang.python)
  • Re: Problem with exec
    ... would look up its globals in namespace, that might be an interesting concept ... The 'thunk' function, defined below, turns a function into code that can be ... def simple_assigns: ...
    (comp.lang.python)