2

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.

1 Answer 1

2

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()
Sign up to request clarification or add additional context in comments.

1 Comment

In case you're interested, I want to make a dictionary of handler functions, and want to avoid adding dozens of lines like handler["foo"] = foo. I'd use lambdas if I could...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.