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]
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.
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.
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.
Python passes arguments neither by reference nor by value, but by assignment.
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"
.
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