Reading the book "Introduction to computer science using Python", by Charles Dierbach, I got a question:
- In page 210, he says "A reference is a value that references, or “points to,” the location of another entity. A variable’s reference value can be determined with built-in function id."
So a reference is just the address in memory of an object.
Now, if I'm not mistaken, when I create a variable like:
>>> a = 3
The name a is put automatically by Python in the namespace.
If I do:
I get the address in memory of the object 3, the one that a is referencing.
So what I want to know is, how are the name a and the reference value related.
I'm guessing that when a name is a put into a namespace, it includes 2 things:
The name itself.
The reference value (id of the object)
A pair like maybe:
If so, is there some instrospection tool to see what an entry in the namespace look like?
Best How To :
Python namespaces are, on the whole, implemented as dictionaries. A key maps to a value, and in a namespace the keys are the identifiers, the names, and the values reference the objects that the names are tied to.
You already found the tool that makes the 'reference' part visible, the
id() function. You can use the
locals() functions to access the namespace mappings:
>>> a = 3
['__builtins__', '__name__', '__doc__', 'a', '__package__']
Note however that in a function, the local namespace has been highly optimised and the dictionary returned by
locals() is just a one-way reflection of the real structure, which is just a C array with references. You can look, but not touch, through this mapping.
If you wanted to further visualise how Python namespaces work, run your code in the Online Python Tutor; it'll show you how the names and Python objects in memory interact.