Dynamically changing the type

An object's type can be checked by using the built-in type:

print(type(3))  # <class 'int'>

You can also access that information directly by checking the dunder attribute __class__:

print((3).__class__)  # <class 'int'>

Apparently, for your own custom types, you can assign to the dunder attribute __class__ and dynamically change the type of an instance.

For example, the variable x below holds an instance of the class A that doesn't have any methods:

class A:
    def __init__(self, value):
        self.value = value

x = A(42)

Now, you can define the class B that defines a method, you can assign x.__class__ to it, and you can call that method:

class B:
    def mult(self, x):
        return self.value * x

x.__class__ = B
print(type(x))  # <class '__main__.B'> !?
print(x.mult(10))  # 420

I learned this in a cool lightning talk given at EuroPython 2025!

Become the smartest Python 🐍 developer in the room πŸš€

Every Monday, you'll get a Python deep dive that unpacks a topic with analogies, diagrams, and code examples so you can write clearer, faster, and more idiomatic code.

Previous Post Next Post

Blog Comments powered by Disqus.