How to change __repr__ for an imported class of immutable type

41 views Asked by At

I am using gmpy2 to work with high-precision floats (>500 bit of precision). My code contains long lists of such floats, e.g.

import gmpy2

gmpy2.get_context().precision = 500
rs = gmpy2.random_state()
lst = [gmpy2.mpfr_random(rs) for _ in range(4)]
print(lst)

# [mpfr('0.271521109675768030046267124634073667684105281814578550174956682310741033886748
#  70742194330013240808110139077875599032334632394117927746462940740105086152',500), mpfr('0.651
#  70987608257463499855942595039172347625432569368637954337608487459435530015416379355871
#  784576133166076679114013337947978739119046252118327755675301311',500), mpfr('0.250491752647
#  45810463315271935029178260478893809777157454094624870772157985848539893902700198
#  946816912841670920043748676653996297679708199369887486126487',500), mpfr('0.35225 ...

As you see in this example, output tends to be unreadable because mpfr.__repr__ prints all digits to the screen. I know in this example I could simply format the output

print([f'{l}' for l in lst])
# ['0.271521', '0.651710', '0.250492', '0.352256']

However, I also have classes that internally contain mpfrs, and it'd be convenient that the automatically generated representations look more compact, for instance with only 10 digits.

I tried overwriting the __repr__ method, but the naive attempt fails:

BigFloat = gmpy2.mpfr
BigFloat.__repr__ = lambda self: 'bigfloat'

# TypeError: cannot set '__repr__' attribute of immutable type 'mpfr'

I also tried creating a new class that inherits from mpfr, but that also does not work

class BigFloat(gmpy2.mpfr):

    def __repr__(self):
        return 'bigfloat'

# TypeError: type 'mpfr' is not an acceptable base type

I know I could create a new class BigFloat that internally contains a gmpy2.mpfr. Then I would reimplement all magic methods like __add__, __neg__, ... based on the mpfr class. But is there a more concise/elegant solution?

0

There are 0 answers