How to fake type with Python How to fake type with Python python python

How to fake type with Python


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

@classmethoddef __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.


Override __class__ in your wrapper class DocumentWrapper:

class DocumentWrapper(object):  @property  def __class__(self):    return User>>> isinstance(DocumentWrapper(), User)True

This way no modifications to the wrapped class User are needed.

Python Mock does the same (see mock.py:612 in mock-2.0.0, couldn't find sources online to link to, sorry).


Testing the type of an object is usually an antipattern in python. In some cases it makes sense to test the "duck type" of the object, something like:

hasattr(some_var, "username")

But even that's undesirable, for instance there are reasons why that expression might return false, even though a wrapper uses some magic with __getattribute__ to correctly proxy the attribute.

It's usually preferred to allow variables only take a single abstract type, and possibly None. Different behaviours based on different inputs should be achieved by passing the optionally typed data in different variables. You want to do something like this:

def dosomething(some_user=None, some_otherthing=None):    if some_user is not None:        #do the "User" type action    elif some_otherthing is not None:        #etc...    else:         raise ValueError("not enough arguments")

Of course, this all assumes you have some level of control of the code that is doing the type checking. Suppose it isn't. for "isinstance()" to return true, the class must appear in the instance's bases, or the class must have an __instancecheck__. Since you don't control either of those things for the class, you have to resort to some shenanigans on the instance. Do something like this:

def wrap_user(instance):    class wrapped_user(type(instance)):        __metaclass__ = type        def __init__(self):            pass        def __getattribute__(self, attr):            self_dict = object.__getattribute__(type(self), '__dict__')            if attr in self_dict:                return self_dict[attr]            return getattr(instance, attr)        def extra_feature(self, foo):            return instance.username + foo # or whatever    return wrapped_user()

What we're doing is creating a new class dynamically at the time we need to wrap the instance, and actually inherit from the wrapped object's __class__. We also go to the extra trouble of overriding the __metaclass__, in case the original had some extra behaviors we don't actually want to encounter (like looking for a database table with a certain class name). A nice convenience of this style is that we never have to create any instance attributes on the wrapper class, there is no self.wrapped_object, since that value is present at class creation time.

Edit: As pointed out in comments, the above only works for some simple types, if you need to proxy more elaborate attributes on the target object, (say, methods), then see the following answer: Python - Faking Type Continued