Search code examples
pythonscopeclosureslocal

Accessing variables in the local scope of a python decorator


Consider:

def g(value):
    def f():
        return value
    return f

x = g(3)
x() # prints 3

Given x in the example, the returned closure from g(3), is there any way to inspect that is the value of value without calling x()?


Solution

  • Yes, you can directly introspect the closure for a function in Python:

    >>> def g(value):
    ...     def f():
    ...         return value
    ...     return f
    ...
    >>> func = g(42)
    >>> func.__closure__
    (<cell at 0x1077b5a80: int object at 0x1075b4618>,)
    

    Then if you want the value:

    >>> cell =  func.__closure__[0]
    >>> cell.cell_contents
    42