Where do nested functions live?

Fredrik Lundh fredrik at pythonware.com
Wed Nov 1 06:55:57 EST 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:

def outer():
     def inner(arg="hello"):
	print arg
     inner()

extract_nested_function(outer, "inner")()

and

def outer():
     arg = "hello"
     def inner():
	print arg
     inner()

extract_nested_function(outer, "inner")()

</F>




More information about the Python-list mailing list