Search code examples
pythonreflectionnested-function

Python: access nested functions by name


Inside a function, I can use dir() to get a list of nested functions:

>>> def outer():
...  def inner(): pass
...  print dir()
...
>>> outer()
['inner']

...but then what? How can I access these functions by name? I see no __dict__ attribute.


Solution

  • First: Are you sure you want to do this? It's usually not a good idea. That said,

    def outer():
        def inner(): pass
        locals()['inner']()
    

    You can use locals to get a dictionary of local variable values, then look up the value of 'inner' to get the function. Don't try to edit the local variable dict, though; it won't work right.


    If you want to access the inner function outside the outer function, you'll need to store it somehow. Local variables don't become function attributes or anything like that; they're discarded when the function exits. You can return the function:

    def outer():
        def inner(): pass
        return inner
    
    nested_func = outer()
    nested_func()