Python `str` subclass not calling `__add__`

Viewed 61

I have a class that extends the python str class, essentially coded as follows:

class MyString(str):
    @staticmethod
    def str_wrap(method):
        def __internal__(*args, **kwargs):
            return_value = method(*args, **kwargs)
            print(method.__name__, type(return_value), *args, **kwargs)
            if type(return_value) is str:
                return MyString(return_value)
            return return_value
        return __internal__

    def __getattribute__(self, item):
        return_value = super().__getattribute__(item)
        if type(return_value) is str and item != "to_string":
             return MyString(return_value)
        if callable(return_value) and item not in ["to_string", "str_wrap"]:
            return self.str_wrap(return_value)
        return return_value

    def to_string(self):
        return str(self)

In my application, I have a line of code as follows, new_str = (old_str + "." + os.path.sep) where old_str is of the type MyString. The problem I'm having is that the type of new_str is str. In my str_wrap function, I have put code to trace what methods are being passed through it, and I noticed that __add__ was never among them. Why is adding strings not calling __add__ through __getattribute__? Am I doing something wrong?

0 Answers
Related