Search code examples
pythonoverloading

How to overload operators on built-in types


Would it be possible to overload '>' as an operator on two strings. This would be nice as it would allow for custom results while debugging. In my case, I could also edit the source code and add prints, etc., but the Monkey Patch is quicker and available without a rebuild.

The desired result would be that typing (for example):

>>>import os
>>>"string1" > "string2"

would call some custom code that I've created. Other options might be to use decorators, or some of the solutions here:

Redirect stdout to a file in Python?


Solution

  • If you derive a class from str I guess you could:

    class pipe_string(str):
        def __gt__(self, other):
            with open(other, "w") as file:
                file.write(self)
    
    pipe_string("foo") > "bar.txt"
    

    But I would discourage it I think. Might be better to send whatever you are looking to send to stdout via python and use your shell to do shell things.