<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by dingdongdash on Medium]]></title>
        <description><![CDATA[Stories by dingdongdash on Medium]]></description>
        <link>https://medium.com/@dingdongdash?source=rss-c44e87d377b8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*qRwo9kOLj9h-FjDV0saIPQ.png</url>
            <title>Stories by dingdongdash on Medium</title>
            <link>https://medium.com/@dingdongdash?source=rss-c44e87d377b8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 11:05:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dingdongdash/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Python 3: Mutable, Immutable... Everything Is an Object!]]></title>
            <link>https://dingdongdash.medium.com/python-3-mutable-immutable-everything-is-an-object-4e4679897a25?source=rss-c44e87d377b8------2</link>
            <guid isPermaLink="false">https://medium.com/p/4e4679897a25</guid>
            <dc:creator><![CDATA[dingdongdash]]></dc:creator>
            <pubDate>Sat, 07 Nov 2026 15:26:56 GMT</pubDate>
            <atom:updated>2026-11-07T15:26:56.925Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x0Ogl4Toqe_KhK1PqYGTbQ.png" /></figure><h3>Introduction</h3><p>When I started the “Python — Everything is object” project at ALU, I assumed a variable was a little box holding a value, the way it works in C. Python doesn’t work like that. Every value, whether it is a number, a string, a list or even a function, is an <strong>object</strong>, and a variable is just a <em>name</em> attached to an object. Once I understood that, things that had confused me (a list changing “by itself”, is returning False for equal numbers) made sense. All outputs below come from Python 3.13.2 on my machine.</p><h3>id and type</h3><p>The <strong>id</strong> of an object is an integer that identifies it uniquely during its lifetime; in CPython it is the object’s memory address. The <strong>type</strong> of an object tells Python what the object is and which operations it supports. Neither changes once the object exists.</p><pre>&gt;&gt;&gt; a = 89<br>&gt;&gt;&gt; id(a)<br>4395677072<br>&gt;&gt;&gt; type(a)<br>&lt;class &#39;int&#39;&gt;</pre><p>The id will be different on your computer, and different on every run. What matters is comparing ids: is checks whether two names point to the <em>same</em> object, while == checks whether the <em>values</em> are equal.</p><h3>Mutable objects</h3><p>A <strong>mutable</strong> object can be changed in place after it is created: its content changes but its id stays the same. The built-in mutable types are list, dict, set and bytearray (plus most classes I define myself).</p><pre>&gt;&gt;&gt; l1 = [1, 2, 3]<br>&gt;&gt;&gt; l2 = l1<br>&gt;&gt;&gt; l2.append(4)<br>&gt;&gt;&gt; l1<br>[1, 2, 3, 4]<br>&gt;&gt;&gt; l1 is l2<br>True</pre><p>l2 = l1 did not copy anything. It created an <strong>alias</strong>: a second name for the same object. Modifying through one name is visible through the other. To get an independent object I have to copy explicitly:</p><pre>&gt;&gt;&gt; l3 = list(l1)<br>&gt;&gt;&gt; l3.append(5)<br>&gt;&gt;&gt; l1, l3<br>([1, 2, 3, 4], [1, 2, 3, 4, 5])<br>&gt;&gt;&gt; l1 is l3<br>False</pre><h3>Immutable objects</h3><p>An <strong>immutable</strong> object can never be modified after creation. The built-in immutable types are int, float, complex, str, tuple, frozenset and bytes. Any operation that looks like a change actually builds a new object.</p><pre>&gt;&gt;&gt; s = &quot;SCHL&quot;<br>&gt;&gt;&gt; s[0] = &quot;X&quot;<br>TypeError: &#39;str&#39; object does not support item assignment   # traceback trimmed<br>&gt;&gt;&gt; s.lower(), s<br>(&#39;schl&#39;, &#39;SCHL&#39;)</pre><p>Here is how an immutable object sits in memory. When I wrote a = 89, Python created an int object and bound the name a to it. Doing b = a binds a second name to the <em>same</em> object. Then a = a + 1 doesn&#39;t touch the 89: it finds or creates a <em>different</em> object (90) and rebinds only a.</p><pre>&gt;&gt;&gt; b = a<br>&gt;&gt;&gt; id(b) == id(a)<br>True<br>&gt;&gt;&gt; a = a + 1<br>&gt;&gt;&gt; a, b<br>(90, 89)<br>&gt;&gt;&gt; id(a) == id(b)<br>False</pre><pre>after b = a:                 after a = a + 1:</pre><pre>a -&gt;  [id 4395677072: 89]    a -&gt;  [another id: 90]<br>b ---^                       b -&gt;  [id 4395677072: 89]</pre><p>This gives me a clear difference between <strong>assignment</strong> and <strong>referencing</strong>: = never copies an object, it only (re)binds a name to an object, and referencing an object through another name gives an alias to that same object.</p><h3>Why it matters</h3><p>Python treats the two families very differently. Immutable objects can’t change, so Python can safely <strong>share</strong> them and use them as dictionary keys (their hash never changes). Mutable objects can change under your feet, so aliasing them is a source of bugs, and they refuse to be hashed:</p><pre>&gt;&gt;&gt; hash((1, [2]))<br>TypeError: unhashable type: &#39;list&#39;</pre><p>This hides a surprising special case: a <strong>tuple</strong> (like a frozenset) is immutable, but it may <em>contain</em> mutable objects. Its stored references never change, but the list behind one of them can:</p><pre>&gt;&gt;&gt; t = (1, [2, 3])<br>&gt;&gt;&gt; id(t), id(t[1])<br>(4388341376, 4388780032)<br>&gt;&gt;&gt; t[1].append(99)<br>&gt;&gt;&gt; t<br>(1, [2, 3, 99])<br>&gt;&gt;&gt; id(t), id(t[1])<br>(4388341376, 4388780032)<br>&gt;&gt;&gt; t[0] = 5<br>TypeError: &#39;tuple&#39; object does not support item assignment   # traceback trimmed</pre><p>Both ids are unchanged, yet the tuple shows different content. “Immutable” means the references can’t change, not that everything inside is frozen.</p><h3>Passing arguments to functions</h3><p>In Python, arguments are passed <strong>by assignment</strong>, often called “pass by object reference”: the parameter name inside the function is bound to the same object the caller passed in. So what happens next depends on mutability.</p><pre>def inc(n):<br>    n += 1<br>    print(&quot;inside:&quot;, n, id(n))</pre><pre>def push(l):<br>    l.append(&quot;new&quot;)<br>    print(&quot;inside:&quot;, l, id(l))</pre><pre>def rebind(l):<br>    l = l + [&quot;z&quot;]<br>    print(&quot;inside:&quot;, l, id(l))</pre><pre>v = 10<br>inc(v)<br>print(&quot;outside:&quot;, v, id(v))</pre><pre>m = [&quot;a&quot;]<br>push(m)<br>print(&quot;outside:&quot;, m, id(m))<br>rebind(m)<br>print(&quot;outside:&quot;, m, id(m))</pre><pre>inside: 11 4321782736<br>outside: 10 4321782704<br>inside: [&#39;a&#39;, &#39;new&#39;] 4301523328<br>outside: [&#39;a&#39;, &#39;new&#39;] 4301523328<br>inside: [&#39;a&#39;, &#39;new&#39;, &#39;z&#39;] 4313497408<br>outside: [&#39;a&#39;, &#39;new&#39;] 4301523328</pre><ul><li>With an <strong>immutable</strong> argument (v), n += 1 can only create a new int, so the caller&#39;s value is unaffected.</li><li>With a <strong>mutable</strong> argument (m), append modifies the shared object, so the caller sees the change: same id inside and outside.</li><li>With l = l + [&quot;z&quot;], I <em>rebind</em> the local name to a brand new list, so the original is untouched. Mutating and rebinding are not the same thing.</li></ul><h3>Advanced: pre-allocated integers</h3><p>CPython creates the integers from -5 to 256 once, at start-up, and reuses them forever. These are NSMALLNEGINTS (5, for -5..-1) and NSMALLPOSINTS (257, for 0..256), so 5 + 257 = <strong>262</strong> integer objects exist before my code even runs. They were chosen because they are the integers programs use the most (loop counters, indexes, small flags), so sharing them saves both memory and allocation time. I checked the boundaries in an interactive session (python3 -i):</p><pre>&gt;&gt;&gt; c = 256<br>&gt;&gt;&gt; d = 256<br>&gt;&gt;&gt; c is d<br>True<br>&gt;&gt;&gt; e = 257<br>&gt;&gt;&gt; f = 257<br>&gt;&gt;&gt; e is f<br>False<br>&gt;&gt;&gt; g = -5<br>&gt;&gt;&gt; h = -5<br>&gt;&gt;&gt; g is h<br>True<br>&gt;&gt;&gt; i = -6<br>&gt;&gt;&gt; j = -6<br>&gt;&gt;&gt; i is j<br>False</pre><p>Careful, because the same idea behaves differently depending on <em>where</em> I run it. In an interactive session each line is compiled separately, so two 1024 literals become two objects:</p><pre>&gt;&gt;&gt; x = 1024<br>&gt;&gt;&gt; y = 1024<br>&gt;&gt;&gt; x is y<br>False<br>&gt;&gt;&gt; x == y<br>True</pre><p>But in a <strong>script</strong> file (python3 ids.py), the compiler sees both literals in the same code block and reuses one constant object:</p><pre>a = 1024<br>b = 1024<br>print(a is b)   # prints True when run as a script</pre><p>Same code, opposite answer, which is why I never use is to compare numbers.</p><h3>Advanced: string interning</h3><p>Python also <em>interns</em> some strings, meaning it keeps one shared copy. Identifier-like strings (letters, digits, underscores) are interned, while strings with spaces typically are not. In my interactive session:</p><pre>&gt;&gt;&gt; s1 = &quot;SCHL&quot;<br>&gt;&gt;&gt; s2 = &quot;SCHL&quot;<br>&gt;&gt;&gt; s1 is s2<br>True<br>&gt;&gt;&gt; s3 = &quot;SCHL is cool&quot;<br>&gt;&gt;&gt; s4 = &quot;SCHL is cool&quot;<br>&gt;&gt;&gt; s3 is s4<br>False</pre><p>This is an implementation detail that can change between versions.</p><h3>Advanced: __slots__</h3><p>By default each instance stores its attributes in a __dict__, so I can add new attributes at any time. Declaring __slots__ removes that dictionary: attributes are limited to the declared names, and instances use less memory.</p><pre>class Plain:<br>    def __init__(self):<br>        self.x = 1</pre><pre>class Slim:<br>    __slots__ = (&quot;x&quot;,)<br>    def __init__(self):<br>        self.x = 1</pre><pre>p, s = Plain(), Slim()<br>p.extra = &quot;ok&quot;<br>print(p.extra)<br>try:<br>    s.extra = &quot;nope&quot;<br>except AttributeError as e:<br>    print(&quot;AttributeError:&quot;, e)<br>print(hasattr(p, &quot;__dict__&quot;), hasattr(s, &quot;__dict__&quot;))</pre><pre>ok<br>AttributeError: &#39;Slim&#39; object has no attribute &#39;extra&#39; and no __dict__ for setting new attributes<br>True False</pre><h3>Advanced: a function with persistent state</h3><p>Default argument values are evaluated <strong>once</strong>, when the function is defined, and stored on the function object. If the default is mutable, it becomes a persistent counter:</p><pre>&gt;&gt;&gt; def counter(c=[0]):<br>...     c[0] += 1<br>...     return c[0]<br>...<br>&gt;&gt;&gt; counter(), counter(), counter()<br>(1, 2, 3)<br>&gt;&gt;&gt; counter.__defaults__<br>([3],)</pre><p>It works, but it is also a classic trap.</p><h3>Conclusion</h3><p>Everything in Python is an object with an id and a type, and names are just labels attached to objects. Mutable objects change in place and can be aliased by accident; immutable ones are replaced, which makes them safe to share. Now I understand why functions can change my lists but never my integers.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4e4679897a25" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Class vs Instance Attributes in Python 3: Where Does Python Look for Your Data?]]></title>
            <link>https://dingdongdash.medium.com/class-vs-instance-attributes-in-python-3-where-does-python-look-for-your-data-e8ed5bd83259?source=rss-c44e87d377b8------2</link>
            <guid isPermaLink="false">https://medium.com/p/e8ed5bd83259</guid>
            <dc:creator><![CDATA[dingdongdash]]></dc:creator>
            <pubDate>Sat, 07 Nov 2026 15:04:24 GMT</pubDate>
            <atom:updated>2026-11-07T15:04:24.815Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MdWlXAgcS7jEezjqXpnVrw.png" /></figure><p>While working on the “More Classes and Objects” project at ALU, I kept running into the same confusion: <em>why does changing one thing on one object sometimes change it everywhere, and sometimes not at all?</em> The answer turned out to be the difference between <strong>class attributes</strong> and <strong>instance attributes</strong>. This post is what I wish I had read before starting. All examples were run with Python 3.13.2, and the outputs shown are the real ones.</p><h3>The three basic words</h3><p><strong>A class</strong> is a blueprint. It describes what objects of that kind will look like and what they can do.</p><pre>class Dog:<br>    species = &quot;Canis familiaris&quot;</pre><pre>    def __init__(self, name):<br>        self.name = name</pre><p><strong>An instance</strong> is one concrete object built from that blueprint.</p><pre>rex = Dog(&quot;Rex&quot;)<br>print(type(Dog), type(rex))</pre><pre>&lt;class &#39;type&#39;&gt; &lt;class &#39;__main__.Dog&#39;&gt;</pre><p><strong>An attribute</strong> is a variable that belongs to an object (or to a class). rex.name is an attribute; so is Dog.species.</p><pre>print(rex.name)<br>print(rex.species)<br>print(Dog.species)</pre><pre>Rex<br>Canis familiaris<br>Canis familiaris</pre><h3>Class attribute vs instance attribute</h3><ul><li>A <strong>class attribute</strong> belongs to the class itself. There is exactly one copy, and every instance can read it.</li><li>An <strong>instance attribute</strong> belongs to one specific object. Each instance has its own copy.</li></ul><p>In Dog, species is a class attribute and name is an instance attribute.</p><h3>All the ways to create them</h3><pre>class Car:<br>    wheels = 4                         # 1. in the class body -&gt; class attribute<br>    def __init__(self, brand):<br>        self.brand = brand             # 2. in __init__ via self -&gt; instance attribute</pre><pre>c = Car(&quot;Kia&quot;)<br>c.color = &quot;red&quot;                        # 3. dynamic assignment on an instance<br>Car.doors = 4                          # 4. assignment on the class<br>setattr(c, &quot;year&quot;, 2020)               # 5. setattr on an instance<br>setattr(Car, &quot;fuel&quot;, &quot;petrol&quot;)         #    ...or on the class</pre><pre>print(c.__dict__)<br>print(c.wheels, c.doors, c.fuel)</pre><pre>{&#39;brand&#39;: &#39;Kia&#39;, &#39;color&#39;: &#39;red&#39;, &#39;year&#39;: 2020}<br>4 4 petrol</pre><p>Notice that wheels, doors and fuel are <em>not</em> in c.__dict__; they live on the class, and c just finds them there.</p><p><strong>What’s the Pythonic way?</strong> For the attributes every object should have, I now declare them in __init__ with self, so a reader sees the full shape of an object in one place. Class attributes go in the class body, for the things that really are shared. Adding attributes on the fly (methods 3–5) works, but it makes objects harder to predict, so I keep it for special cases like setattr with a name that is only known at runtime.</p><p>For “private-ish” data, Python has no real private attributes. The convention is a leading underscore, and a <strong>property</strong> lets you control access:</p><pre>class Account:<br>    def __init__(self, balance):<br>        self._balance = balance<br>    @property<br>    def balance(self):<br>        return self._balance<br>    @balance.setter<br>    def balance(self, value):<br>        if value &lt; 0:<br>            raise ValueError(&quot;balance cannot be negative&quot;)<br>        self._balance = value</pre><pre>a = Account(10)<br>a.balance = 50<br>print(a.balance)<br>try:<br>    a.balance = -1<br>except ValueError as e:<br>    print(&quot;ValueError:&quot;, e)</pre><pre>50<br>ValueError: balance cannot be negative</pre><h3>How Python looks up an attribute</h3><p>Every object keeps its attributes in a dictionary called __dict__. When I write rex.species, Python:</p><ol><li>looks in rex.__dict__ (the instance),</li><li>if not found, looks in Dog.__dict__ (the class),</li><li>if still not found, raises AttributeError.</li></ol><pre>rex.attr  -&gt;  [ rex.__dict__ ]  -&gt;  [ Dog.__dict__ ]  -&gt;  AttributeError</pre><p>Let’s watch it happen:</p><pre>rex = Dog(&quot;Rex&quot;)<br>print(rex.__dict__)<br>print({k: v for k, v in Dog.__dict__.items() if not k.startswith(&quot;__&quot;)})<br>print(rex.species, &quot;species&quot; in rex.__dict__)</pre><pre>{&#39;name&#39;: &#39;Rex&#39;}<br>{&#39;species&#39;: &#39;Canis familiaris&#39;}<br>Canis familiaris False</pre><p>species is found, but not on the instance. Now I assign to it through the instance:</p><pre>rex.species = &quot;Wolf&quot;<br>print(rex.__dict__)<br>print(rex.species, Dog.species)<br>del rex.species<br>print(rex.species)<br>try:<br>    rex.age<br>except AttributeError as e:<br>    print(&quot;AttributeError:&quot;, e)</pre><pre>{&#39;name&#39;: &#39;Rex&#39;, &#39;species&#39;: &#39;Wolf&#39;}<br>Wolf Canis familiaris<br>Canis familiaris<br>AttributeError: &#39;Dog&#39; object has no attribute &#39;age&#39;</pre><p>This was my big “aha”: rex.species = &quot;Wolf&quot; did <strong>not</strong> change the class. It created a <em>new</em> instance attribute that <strong>shadows</strong> the class one. Deleting it makes the lookup fall through to the class again.</p><h3>What happens when a class attribute changes</h3><pre>class Config:<br>    timeout = 30</pre><pre>x, y = Config(), Config()<br>y.timeout = 5          # y shadows the class value<br>Config.timeout = 60    # change the class attribute<br>z = Config()           # created after the change</pre><pre>print(x.timeout, y.timeout, z.timeout)</pre><pre>60 5 60</pre><ul><li>x never had its own timeout, so it sees the new value.</li><li>z, created later, also gets 60.</li><li>y shadowed the attribute, so it keeps its own 5.</li></ul><h3>Differences, advantages and drawbacks</h3><ul><li><strong>Lives in</strong>: Class attribute: Class.__dict__; Instance attribute: instance.__dict__</li><li><strong>Copies</strong>: Class attribute: one, shared; Instance attribute: one per object</li><li><strong>Changing it</strong>: Class attribute: affects every instance that hasn’t shadowed it; Instance attribute: affects only that object</li></ul><p><strong>Class attributes — advantages:</strong> one copy saves memory, and one change updates everything that relies on it. <strong>Drawbacks:</strong> the shared state can surprise you, especially with mutable values:</p><pre>class Tag:<br>    labels = []                 # shared mutable list<br>    def __init__(self, name):<br>        self.name = name</pre><pre>a, b = Tag(&quot;a&quot;), Tag(&quot;b&quot;)<br>a.labels.append(&quot;python&quot;)<br>print(b.labels)<br>print(a.labels is b.labels)</pre><pre>[&#39;python&#39;]<br>True</pre><p>I only touched a, yet b has the label too: .append mutates the one list on the class. The fix is to create the list per instance:</p><pre>class TagFixed:<br>    def __init__(self, name):<br>        self.name = name<br>        self.labels = []</pre><pre>a, b = TagFixed(&quot;a&quot;), TagFixed(&quot;b&quot;)<br>a.labels.append(&quot;python&quot;)<br>print(b.labels)</pre><pre>[]</pre><p><strong>Instance attributes — advantages:</strong> each object is independent and safe to modify. <strong>Drawbacks:</strong> every object stores its own copy, so values that never change cost extra memory and must be set up in every __init__.</p><h3>When I use class attributes</h3><ul><li><strong>Constants</strong> shared by all objects (PI = 3.14159).</li><li><strong>Default values</strong> that an instance may override (color = &quot;black&quot;).</li><li><strong>Tracking values across instances</strong>, like a counter such as number_of_instances.</li></ul><pre>class Circle:<br>    PI = 3.14159<br>    color = &quot;black&quot;<br>    number_of_instances = 0<br>    def __init__(self, r, color=None):<br>        self.r = r<br>        if color is not None:<br>            self.color = color<br>        Circle.number_of_instances += 1<br>    def area(self):<br>        return self.PI * self.r ** 2</pre><pre>c1, c2 = Circle(2), Circle(1, &quot;red&quot;)<br>print(c1.color, c2.color, Circle.number_of_instances, round(c1.area(), 2))</pre><pre>black red 2 12.57</pre><p>One trap here: the counter must be updated through the <strong>class</strong> name. If I write c1.number_of_instances += 1, Python reads the class value, adds 1, and stores the result on c1, shadowing the class attribute:</p><pre>c1.number_of_instances += 1<br>print(c1.__dict__, Circle.number_of_instances)</pre><pre>{&#39;r&#39;: 2, &#39;number_of_instances&#39;: 3} 2</pre><p>The class counter is still 2, and c1 now has its own private 3.</p><h3>Conclusion</h3><p>The rule I took away: <strong>reading</strong> an attribute looks at the instance first, then the class; <strong>assigning</strong> through an instance always creates or updates an <em>instance</em> attribute. Use __init__ for per-object data, class attributes for constants, defaults and shared counters, and be careful with mutable class attributes. Whenever I&#39;m confused, printing instance.__dict__ and Class.__dict__ shows exactly where the value lives.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e8ed5bd83259" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>