Search code examples
pythonmagic-methods

Can magic methods return different result type?


Can a magic method like def __sub__() which operates on a type return a different result type?

For example in below class User, the -1 operator returns a string. The requirement is if there is difference return a string showing representation of the difference.

import copy
class User:
    def __init__(self, username=""):
        self.__user_name = username
    
    def __sub__(self,other):
        if other.__user_name != self.__user_name:
            return "User name changed from {} to {}".format(self.__user_name,
            other.__user_name);
        else:
            return ""
            
    def set_user_name(self, username):
        self.__user_name = username
            
            
user_1 = User("John")
user_2 = copy.copy(user_1)
user_2.set_user_name("Tom")
user_diff = user_1 - user_2

After which if we print user_diff it will be "User name changed from John to Tom" .

Is this allowed and one of the way to show the difference, mainly the '-' returning a different object type (string) as compared to User?


Solution

  • Sure: a prominent example in the standard library is datetime.__sub__, which returns a timedelta instance when the other operand is another datetime instance.

    >>> d1 = datetime.datetime.now()
    >>> d2 = datetime.datetime.now()
    >>> type(d2 - d1)
    <class 'datetime.timedelta'>