Question

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?

Was it helpful?

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.

OTHER TIPS

Simple answer is to not use type() for my_class, instead use a string:

raise TypeError(err_msg.format("<type 'my_class'>", type(other)))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top