Is it possible to do something like
c = MyObj()
c.eval(\"func1(42)+func2(24)\")
in Python..i.e. have func1() and func2() be evaluated within th
So, I advice you to do something like this:
>>> class S(object):
... def add(self, a, b):
... return a + b
...
>>> filter(lambda (k,v): not k.startswith("__"), S.__dict__.items())
[('add', )]
>>> target = S()
>>> map(lambda (k, f): (k, f.__get__(target, S)), filter(lambda (k,v): not k.startswith("__"), S.__dict__.items()))
[('add', >)]
>>> dict(_)
{'add': >}
>>> eval("add(45, 10) + add(10, 1)", _, {})
66
Seems like that you need. Let me explain how this works.
eval
accepts locals and globals as parameters. globals
dictionary of all "valuable" bounded methods.S
class definition. How to get all "valuable" methods? Simple filter
names from S.__dict__
in order to check whether method name starts from __
or not (you see, that as result we get list with 1 item - add
function).target
= instance of S
class which will be "eval context".__dict__
stores functions, each function is non-data descriptor and bounded method can be fetched simply with func.__get__(obj, type(obj))
. This operation is performed in map
.dict
from it.globals
to eval
function.I hope, this will help.