How to fake type with Python

Pierre picture Pierre · Jul 24, 2011 · Viewed 9.8k times · Source

I recently developed a class named DocumentWrapper around some ORM document object in Python to transparently add some features to it without changing its interface in any way.

I just have one issue with this. Let's say I have some User object wrapped in it. Calling isinstance(some_var, User) will return False because some_var indeed is an instance of DocumentWrapper.

Is there any way to fake the type of an object in Python to have the same call return True?

Answer

Katriel picture Katriel · Jul 24, 2011

You can use the __instancecheck__ magic method to override the default isinstance behaviour:

@classmethod
def __instancecheck__(cls, instance):
    return isinstance(instance, User)

This is only if you want your object to be a transparent wrapper; that is, if you want a DocumentWrapper to behave like a User. Otherwise, just expose the wrapped class as an attribute.

This is a Python 3 addition; it came with abstract base classes. You can't do the same in Python 2.