Python Object References, Mutability, and Garbage Collection

Understanding Python Variables

Python variibles function differently from those in Java. In Pytthon, variables act as pointers that referance objects of various types like integers or strings. Think of them as sticky notes that can attach to different objects.

Java variables work more like containers where you declare a specific type and store values within that container.

value = 1
value = "xyz"

In the first case, an integer object containing 1 is created, then the variable value points to this object with a fixed memory footprint.

In the second case, a string object containing 'xyz' is created, and value now points to this new string object.

Differences Between == and is

The == operator checks whether two objects have equal values.

The is operator verifies if two variables point to the same memory location.

x = [5, 6, 7, 8]
y = [5, 6, 7, 8]

# Check if both variables point to same memory address
cprint(x is y)
print(isinstance(x, list))

# Check if the values are equivalent
print(x == y)

del Statement and Memory Management

Python employs reference counting for memory management.

When an object is created and assigned, its reference count increases by one. When a reference is removed using del, the count decreases. When the count reaches zero, the object is deallocated.

# CPython uses reference counting for garbage collection
temp_obj = object()  # Object's ref count increases by 1
another_ref = temp_obj  # Object's ref count increases by 1
del temp_obj  # Object's ref count decreases by 1

Common Default Parameter Pitfall

When using mutable default arguments like lists, reusing the default parameter across multiple function calls can lead to shared state issues.

class Organization:
    def __init__(self, title, members=None):
        self.title = title
        self.members = members if members is not None else []
    
    def add_member(self, member_name):
        self.members.append(member_name)
    
    def remove_member(self, member_name):
        self.members.remove(member_name)

if __name__ == "__main__":
    org1 = Organization("org1", ["alice", "bob"])  # Override default list
    org1.add_member("charlie")
    org1.remove_member("alice")
    print(org1.members)

    org2 = Organization("org2")  # Use default empty list
    org2.add_member("diana")
    print(org2.members)

    print(Organization.__init__.__defaults__)  # View method defaults

    org3 = Organization("org3")  # Uses same default list as org2
    org3.add_member("eve")  # org2 and org3 now share the same list
    print(org2.members)
    print(org3.members)
    print(org2.members is org3.members)

The output demonstrates how instances can inadvertently share the same mutable default argument.

Tags: python Object References Mutability garbage collection Memory Management

Posted on Mon, 05 Oct 2026 16:07:58 +0000 by SirChick