How is the name and its reference value related?

While reading the book Introduction to Computer Science with Python, Charles Dierbach, I asked a question:

  • On page 210 he says: β€œA link is a value that refers or points to the location of another object. The value of a variable reference can be determined using the built-in function identifier.”

So, a link is just an address in the memory of an object.

Now, if I am not mistaken, when I create a variable of the type:

>>> a = 3 

The name a is automatically placed by Python in the namespace .

If I do this:

 >>> id(a) 4548344816 

I get the address in memory of object 3 , which refers to a .

So, I want to know how the name a and the reference value are related.

I assume that when a name is placed in a namespace, it includes 2 things:

  • name

  • reference value (object identifier)

A pair, for example, could be: a:reference value ?

If so, is there any instrospection tool to see what the namespace entry looks like?

+6
source share
1 answer

Python namespaces are generally implemented as dictionaries. The key displays the value, and in the namespace, the keys are identifiers, names and values ​​refer to the objects to which the names are attached.

You have already found a tool that makes the visible part a β€œlink”, with the id() function. You can use the globals() and locals() functions to access namespace mappings:

 >>> a = 3 >>> globals().keys() ['__builtins__', '__name__', '__doc__', 'a', '__package__'] >>> globals()['a'] 3 >>> id(globals()['a']) 4299183224 >>> id(a) 4299183224 

Note, however, that in the function, the local namespace has been greatly optimized, and the dictionary returned by locals() is just a one-way reflection of the real structure, which is just an array of C with links. You can look, but not touch, through this juxtaposition.

If you want to further visualize how Python namespaces work, run your code in the Online Python Tutor ; it will show you how Python names and objects interact in memory.

+5
source

Source: https://habr.com/ru/post/982131/


All Articles