-2

When I writing some Python codes using dict, I found out the following behavior of my code:

In [1]: def foo(bar_dict):
   ...:     print id(bar_dict)
   ...:     bar_dict['new'] = 1
   ...:     return bar_dict
   ...: 

In [2]: old_dict = {'old':0}

In [3]: id(old_dict)
Out[3]: 4338137920

In [4]: new_dict = foo(old_dict)
4338137920

In [5]: new_dict
Out[5]: {'new': 1, 'old': 0}

In [6]: id(new_dict)
Out[6]: 4338137920

In [7]: old_dict
Out[7]: {'new': 1, 'old': 0}

In [8]: id(old_dict)
Out[8]: 4338137920

The old_dict, new_dict and the bar_dict inside the foo function are all point to on memory address. There is only one actually dict object stored in the memory, even I pass a dict inside a function.

I want to know more detail about this kind of memory management mechanism of Python, can anyone points me some good references explain about this? Also, when we use list, set or str in Python, is there any similar behavior?

YaOzI
  • 16,128
  • 9
  • 76
  • 72

1 Answers1

2

Python names are just references to objects stored on a heap. Handing objects to a function call just passes in those references, binding the argument name to the same object.

You created a dictionary object, and bound old_dict to that object. You then passed that name to the foo() function, binding the local name bar_dict to the same object. In the function you then manipulated that object, and returned it. You stored a reference to the returned object in new_dict, resulting in two global names referencing the same object.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343