views:

43

answers:

2

I need to explain how Python variables are references to objects to a collegue. E.g., how changing the value of an object in one place changes other variables that reference it.

I remember reading a wonderful tutorial on that a long time ago. It had diagrams with lines connecting the variables to the objects and showed how those connections changed.

But I can't seem to find it anywhere. I was hoping someone could point me to it.

A: 

Here is a decent tutorial on the subject: Tutorial

If you want something more advanced, try this: Advanced tutorial

Michael Goldshteyn
A: 

Unless I'm missing the point, a basic example should suffice.

local_data is first declared to be a reference to the data list in another module. When it is updated, the list in the module is updated, because they are two names for the same object-- the id() function tells us that they are the same object. Later, when local_data is reassigned to reference a newly created list object, it's id changes.

module.py

data = []
def foo():
    print 'foo', id(data), data

main.py

import module

module.foo()
local_data = module.data
print '  1', id(local_data), local_data
local_data.append('a')
print '  2', id(local_data), local_data
module.foo()
local_data = []
local_data.append('b')
print '  3', id(local_data), local_data
module.foo()

output:

foo 4299514008 []
  1 4299514008 []
  2 4299514008 ['a']
foo 4299514008 ['a']
  3 4299651552 ['b']
foo 4299514008 ['a']
ma3