Home > OS >  How to change float('inf') representation?
How to change float('inf') representation?

Time:12-01

I want to change float('inf') representation -> ∞, can u help me with it? I try to use this, but it didn't work

class Inf(float('inf')):
    def __repr__(self) -> str:
        return '∞'

inf=Inf()

those, when I use print() I want to see '∞' instead 'inf'

I want result like in

from sympy import oo

but get it with oop

CodePudding user response:

drop the ('inf') in class inheritance. You inherit from classes, not their instances. Then in __repr__ check if your float is infinity.

class FloatWithGlyphInf(float):
    def __repr__(self) -> str:
        if self == float('inf'):
            return '∞'
        else:
            return super().__repr__()

print(FloatWithGlyphInf('inf')) # ∞
print(FloatWithGlyphInf('0'))   # 0.0
  • Related