3

Given below snippet code in python Idle, why the sys.getrefcount(a) returns 4?

Given below snippet of code when executed in python idle

import sys
a = []
b = a
sys.getrefcount(a)            # returns 3
a
sys.getrefcount(a)            #returns 4
print(a)
sys.getrefcount(a)             #returns 3

Can anyone please explain why reference count gets increased to 4?

Samrat
  • 101
  • 1
  • 8
  • 2
    Please don't post screenshots of your code, it should be included in your question – roganjosh Sep 01 '18 at 14:05
  • 1
    All code needs to be posted here as text. And what were you expecting it to return? – Carcigenicate Sep 01 '18 at 14:06
  • @roganjosh m extremely sorry for not following the norms to post in the stackoverflow as I was unaware of it. I will keep this in mind from next time onwards. – Samrat Sep 01 '18 at 14:30
  • [Why not upload images of code on SO when asking a question?](https://meta.stackoverflow.com/questions/285551/why-not-upload-images-of-code-on-so-when-asking-a-question) – martineau Sep 01 '18 at 14:31
  • @Carcigenicate Apologies for the mistake. As m new in the stackoverflow . I have edited the question. Can you explain me why the count of reference gets increased to 4 ? – Samrat Sep 01 '18 at 14:34

2 Answers2

6

Let's count:

>>> import sys
>>> a = []
>>> sys.getrefcount(a)
2

We have two references, one under the name "a" and one argument to the function (see here).

>>> b = a
>>> sys.getrefcount(a)
3

"a", "b", and the function arg.

>>> a
[]
>>> sys.getrefcount(a)
4

Where'd the fourth come from? We're using the REPL, and in the repl we get a reference to the last (non-None) value under the name _:

>>> a
[]
>>> _
[]

If you add print around sys.getrefcount(a) and run it as a script, outside of the REPL (where there's no _ magic), you'll see 3.

DSM
  • 342,061
  • 65
  • 592
  • 494
1

I can reproduce what you see in an interactive python shell. What happens is that when you do

>>> a
[]

you create an automatic reference in the variable _ which always stores the value of the last unassigned expression. This is why after entering just a into your REPL you get an additional reference: _ now points to the value a. I presume IDLE behaves the same way.