Reading the book "Introduction to computer science using Python", by Charles Dierbach, I got a question:
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:
>>> id(a)
4548344816
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: a:reference value
?
If so, is there some instrospection tool to see what an entry in the namespace look like?
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 globals()
and locals()
functions to access the 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 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With