Search code examples
pythonmagic-methods

Custom Ouput of type() in Python


How would I customize the output of a type() call against my class?

I am implementing the __add__ method in my class. If the user tries to use it incorrectly I'm raising a TypeError with the following message:

err_msg = "unsupported operand type(s) for -: '{}' and '{}'"
raise TypeError(err_msg.format(type(self), type(other)))

The output reads:

TypeError: unsupported operand type(s) for +: '<type 'instance'>' and '<type 'int'>'

What would I need to do for it to read '<type 'my_class'>' instead?


Solution

  • You don't want to change what type returns. You want to make your class a new-style one which (apart from many other advantages) means the string representation of this class object will mention its name, like all proper types (including but not limited to builtins). Change

    class my_class:
        ...
    

    to

    class my_class(object):
        ...
    

    If my_class inherits from another class which is old-style itself, make that class new-stlye instead.