Where do nested functions live?
fredrik at pythonware.com
Wed Nov 1 12:55:57 CET 2006
Carl Banks wrote:
> Not so fast. You can get at the nested function by peeking inside code
> objects (all bets off for Pythons other than CPython).
> import new
> def extract_nested_function(func,name):
> codetype = type(func.func_code)
> for obj in func.func_code.co_consts:
> if isinstance(obj,codetype):
> if obj.co_name == name:
> return new.function(obj,func.func_globals)
> raise ValueError("function with name %s not found in %r"
> % (name,func))
that doesn't give you the actual nested function, though; just another
function object created from the same code object. and doing this right
is a bit harder than you make it look; your code fails in somewhat
confusing ways on straightforward things like:
arg = "hello"
More information about the Python-list