Home > Net >  CLOSURE : retrieve a variable given with the outer function
CLOSURE : retrieve a variable given with the outer function

Time:06-10

Is it possible to retrieve a variable, which is given with the outer function?

Python :

def html_tag(tag):
    print(" : <{t}>".format(t=tag))
    def wrap_text(msg):
        print("<{t}>{m}<{t}>".format(t=tag, m=msg))

    return wrap_text


print_h1 = html_tag("h1")
print_div = html_tag("div")
print_span = html_tag("span")
print_h1("h1 - test met h1")
print_div("div - mouse button")
print_span("span - tekst met tag")

In my case I would like to see/retrieve the variable tag in the different functions.

link to the excuted python code

print ( "help(print_h1)   : ", help(print_h1), "")
print ( "dir(print_h1)    : ", dir(print_h1), "")
print ( "print_h1.__dir__ : ", (print_h1.__dir__), "")
#print (print_h1.tag, "")
print ( "print_h1         : ",print_h1.__closure__, "\n")
print ( "print_h1         : ",print_h1, "\n")

returns :

Help on function wrap_text in module __main__:

wrap_text(msg)

help(print_h1)   :  None 
dir(print_h1)    :  ['__annotations__', '__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__get__', '__getattribute__', '__globals__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__kwdefaults__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__'] 
print_h1.__dir__ :  <built-in method __dir__ of function object at 0x7f2f42fbdb90> 
print_h1         :  (<cell at 0x7f2f42f73310: str object at 0x7f2f51f066b0>,) 

print_h1         :  <function html_tag.<locals>.wrap_text at 0x7f2f42fbdb90> 

SO WHEN I TRY IT LIKE THIS it is not in the dictionary of the .__dir__ ...

print (print_h1.tag)

ERROR

AttributeError                            Traceback (most recent call last)
<ipython-input-55-71ea208bcc8c> in <module>()
----> 1 print (print_h1.tag)

AttributeError: 'function' object has no attribute 'tag'

EDIT - I would like to retrieve the tag variable

print_h1.__closure__:  (<cell at 0x7f2f42f73310: str object at 0x7f2f51f066b0>,)

address memory location : x - is manual retrieved from previous command

import ctypes

x=0x7f2f51f066b0
# display memory address
print("Memory address - ", x)
  
# get the value through memory address
a = ctypes.cast(x, ctypes.py_object).value
  
# display
print("Value - ", a)

returns :

Memory address -  139841214899888
Value -  h1

CodePudding user response:

__closure__ is an (read-only) attribute of a user-defined function object: it is tuple (or None) of cells that contain bindings for the function’s free variables.

A cell object has the (read & write) attribute cell_contents. This can be used to get/set the value of the cell.

Note cell types can be accessed through types module


code objects are an internal type used by the interpreter and accessible by the user.

co_freevars is a tuple containing the names of free variable


Here an example on how to get the value of the function's parameter and its identifier:

# html_tag: from the question

print_h1 = html_tag('h1')

# identifier of the parameter - with code obj
print(print_h1.__code__.co_freevars[0])
#tag

# value of the function's parameter - read
print(print_h1.__closure__[0].cell_contents)
#h1

# value of the function's parameter - write
print_h1.__closure__[0].cell_contents = 'h19'
print_h1('a')
#<h19>a<h19>
  • Related