Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

In Python, how to override the arithmetic operator "/" to produce: 1 / 0 => math.inf?

In Python, when I run the operation: 1 / 0, its default behavior is generating an exception: "ZeroDivisionError: float division by zero"

How to overload this default behavior so that I can get:
1 / 0 => math.inf

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You need to define your own class and within that define methods __truediv__ (/) and __floordiv__ (//) at a minimum. If you only define those two + for example would not work (see error below).

import math


class MyFloat:
    def __init__(self, val):
        self.val = val

    def __truediv__(self, other):
        if other.val == 0:
            return math.inf
        return self.val / other.val

    def __floordiv__(self, other):
        if other.val == 0:
            return math.inf
        return self.val // other.val


one = MyFloat(1)
zero = MyFloat(0)

print(one / zero)
print(one // zero)
// will throw an error (PyCharm will also pick up on this)
print(one + zero)

Expected output

Traceback (most recent call last):
  File "/home/tom/Dev/Studium/test/main.py", line 24, in <module>
    print(one + zero)
TypeError: unsupported operand type(s) for +: 'MyFloat' and 'MyFloat'
inf
inf

For a list of those special Python function see this website.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading