4

from pydocs

Like its identity, an object’s type is also unchangeable. [1]

from footnote

It is possible in some cases to change an object’s type, under certain controlled conditions. It generally isn’t a good idea though, since it can lead to some very strange behaviour if it is handled incorrectly.

What are the cases when we can change the object's type and how to change it

1

1 Answer 1

2
class A:
    pass

class B:
    pass

a = A()

isinstance(a, A)  # True
isinstance(a, B)  # False
a.__class__  # __main__.A

# changing the class
a.__class__ = B

isinstance(a, A)  # False
isinstance(a, B)  # True
a.__class__  # __main__.B

However, I can't recall real-world examples where it can be helpful. Usually, class manipulations are done at the moment of creating the class (not an object of the class) by decorators or metaclasses. For example, dataclasses.dataclass is a decorator that takes a class and constructs another class on the base of it (see the source code).

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.