Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python sys.getrefcount() shows unexpected 4th reference

I'm looking for an explanation about why I have an unexpected reference count. Yes, I already know sys.getrefcount() will increment the expected count by 1. That is not what's happening below.

I expect the function test(a) to show 3 not 4. Where is the 4th reference coming from?

In [2]: import sys

In [3]: a = []

In [4]: sys.getrefcount( a )
Out[4]: 2

In [5]: def test( x ): print "x ref count = {}".format( sys.getrefcount( x ) )

In [6]: test( a )
x ref count = 4

In [7]: sys.getrefcount( a )
Out[7]: 2
like image 659
sudobangbang Avatar asked Oct 19 '25 15:10

sudobangbang


1 Answers

The stack is the 4th reference.

In order to send the value of a to the function, Python evaluates a first and puts the result on the top of the stack. That is a reference, just like the x variable in the test() function is a reference.

You can see this in the bytecode:

>>> import dis
>>> dis.dis(compile('test( a )', '', 'eval'))
  1           0 LOAD_NAME                0 (test)
              3 LOAD_NAME                1 (a)
              6 CALL_FUNCTION            1
              9 RETURN_VALUE        

The CALL_FUNCTION opcode loads the arguments from the stack (the 1 here means load 1 positional argument from the stack) before invoking the object found next on the stack (the object referenced by test, put there by LOAD_NAME).

This is the exact same reason why the sys.getrefcount() call adds an extra reference; there too the object first has to be added to the stack before the function can be called.

like image 111
Martijn Pieters Avatar answered Oct 21 '25 06:10

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!