Understanding reference count of class variable
<p>This is an attempt to better understand how reference count works in Python.</p>

<p>Let's create a class and instantiate it. The instance's reference count would be <code>1</code> (<code>getrefcount</code> displays <code>2</code> because it's own internal structures reference that class instance increasing reference count by <code>1</code>):</p>

<pre><code>&gt;&gt;&gt; from sys import getrefcount as grc
&gt;&gt;&gt; class A():
    def __init__(self):
        self.x = 100000


&gt;&gt;&gt; a = A()
&gt;&gt;&gt; grc(a)
2
</code></pre>

<p><code>a</code>'s internal variable <code>x</code> has <code>2</code> references:</p>

<pre><code>&gt;&gt;&gt; grc(a.x)
3
</code></pre>

<p>I expected it to be referenced by <code>a</code> and by <code>A</code>'s <code>__init__</code> method. Then I decided to check.</p>

<p>So I created a temporary variable <code>b</code> in the <code>__main__</code> namespace just to be able to access the variable <code>x</code>. It increased the ref-number by <code>1</code> for it to become <code>3</code> (as expected):</p>

<pre><code>&gt;&gt;&gt; b = a.x
&gt;&gt;&gt; grc(a.x)
4
</code></pre>

<p>Then I deleted the class instance and the ref count decreased by <code>1</code>:</p>

<pre><code>&gt;&gt;&gt; del a
&gt;&gt;&gt; grc(b)
3
</code></pre>

<p>So now there are <code>2</code> references: one is by <code>b</code> and one is by <code>A</code> (as I expected).</p>

<p>By deleting <code>A</code> from <code>__main__</code> namespace I expect the count to decrease by <code>1</code> again.</p>

<pre><code>&gt;&gt;&gt; del A
&gt;&gt;&gt; grc(b)
3
</code></pre>

<p>But it doesn't happen. There is no class <code>A</code> or its instances that may reference <code>100000</code>, but still it's referenced by something other than <code>b</code> in <code>__main__</code> namespace.</p>

<p>So, my question is, what is <code>100000</code> referenced by apart from <code>b</code>?</p>

<hr>

<p><strong>BrenBarn</strong> suggested that I should use <code>object()</code> instead of a number which may be stored somewhere internally.</p>

<pre><code>&gt;&gt;&gt; class A():
    def __init__(self):
        self.x = object()


&gt;&gt;&gt; a = A()
&gt;&gt;&gt; b = a.x
&gt;&gt;&gt; grc(a.x)
3
&gt;&gt;&gt; del a
&gt;&gt;&gt; grc(b)
2
</code></pre>

<p>After deleting the instance <code>a</code> there were only one reference by <code>b</code> which is very logical.</p>

<p>The only thing that is left to be understood is why it's not that way with number <code>100000</code>.</p>
