how to make a code object a function
Peter Otten
__peter__ at web.de
Sun Jan 4 11:27:00 EST 2004
Diez B. Roggisch wrote:
> Interesting - from the docs, I can't see that types.MethodType has a
> constructor like this.
It get's really funny if you look into the source (types.py):
class _C:
def _m(self): pass
ClassType = type(_C)
UnboundMethodType = type(_C._m) # Same as MethodType
_x = _C()
InstanceType = type(_x)
MethodType = type(_x._m)
Seems we caught them cheating here :-)
> Just out of curiosity - is there a way to know the name of a code object
> you know nothing about except that it will become a function definition? I
> guess I could go for some AST-stuff looking for a "def foo" statement, so
> I know I will end up having defined foo when exec'ing the code object.
You could provide a separate namespace and then extract only the callables:
>>> d = {}
>>> exec "factor=2\ndef alpha(s, t): print factor*t" in d
>>> d.keys()
['__builtins__', 'alpha', 'factor']
>>> funcs = dict([(n,f) for n, f in d.iteritems() if callable(f)])
>>> funcs
{'alpha': <function alpha at 0x4029025c>}
>>> funcs["alpha"](None, 2)
4
Peter
More information about the Python-list
mailing list