Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does refs increase 2 for every new object in Python?

It is a little weird to me that the refs number in the interactive environment increases 2 after a new object is defined. I created only one object, isn't it?

>>> v
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'v' is not defined
[41830 refs]
>>> v = "v"
[41832 refs]
like image 365
Thomson Avatar asked Feb 14 '11 11:02

Thomson


People also ask

Is multiple references to same object possible in Python?

The net effect is that the variables x and y wind up referencing the same object. This situation, with multiple names referencing the same object, is called a Shared Reference in Python. This statement causes the creation of a new object and made y to reference this new object.

Why does Python use reference counting?

Yes, there is a benefit of earlier collection with reference counting, but the main reason CPython uses it is historical. Originally there was no garbage collection for cyclic objects so cycles led to memory leaks. The C APIs and data structures are based heavily around the principle of reference counting.

What is reference count of an object in Python?

Reference counting is one of the memory management technique in which the objects are deallocated when there is no reference to them in a program. Let's try to understand with examples. Variables in Python are just the references to the objects in the memory.

Does Python pass objects by reference?

Python passes arguments neither by reference nor by value, but by assignment.


1 Answers

Your assignment worked by creating an entry in the globals() dictionary that has v as a key and "v" as a value. That's two references (one for the key and one for the value) although in this case they probably both refer to the same string "v".

like image 71
Duncan Avatar answered Sep 19 '22 01:09

Duncan