Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How are a name and its reference value related?

Tags:

python

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:

>>> 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:

  1. The name itself.

  2. 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?

like image 214
Bobby Wan-Kenobi Avatar asked Feb 07 '15 13:02

Bobby Wan-Kenobi


1 Answers

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.

like image 121
Martijn Pieters Avatar answered Sep 24 '22 02:09

Martijn Pieters