1

How can I identify whether or not a given function is:

  1. A closure function
  2. A nested function which isn't a closure
  3. Not a nested function

I know I can say len(function.__closure__) > 0 but this would only answer whether or not this is a closure. What about a non-closure nested function? And is there a better way to do this?

5
  • All nested functions are closures, whether or not there is anything to actually close over. Commented Feb 12, 2019 at 17:59
  • Why do you need to know this? If the function doesn't close over any variables, the fact that it's nested makes no difference. Commented Feb 12, 2019 at 18:01
  • 1
    What do you need this for, what is the problem you are trying to solve? Commented Feb 12, 2019 at 18:01
  • @MartijnPieters I'm poking around with code injection into existing functions at runtime, and have realized I need to treat closures differently while doing so. Commented Feb 12, 2019 at 18:04
  • @AvivCohn: only if there are closed-over names. If you are patching such functions, see Can you patch *just* a nested function with closure, or must the whole outer function be repeated?. Commented Feb 12, 2019 at 18:06

1 Answer 1

3

The only difference between a nested function with an empty closed-over set of names, and a function defined at the module level, is their __qualname__. All functions have a __closure__ attribute, which is empty when there is no closed-over set of names.

The __qualname__ attribute is writeable, so is not a reliable way of detecting a nested function, but you could look for the string .<locals>. in it:

>>> def foo():
...     def bar():
...         pass
...     return bar
...
>>> foo().__qualname__
'foo.<locals>.bar'

Nested functions that do use closed-over names, will have a non-empty __closure__ tuple.

Sign up to request clarification or add additional context in comments.

Comments

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.