How can I override the __str__ method for sympy.core.numbers.Float?

I am trying to overcome the disadvantages of subclassing a Python float using a different class hierarchy. However, the following code:

from sympy import * import sympy.core.numbers f = 1.123456789 n = N(f, 8) print n print type(n) sympy.core.numbers.Float.__str__ = lambda f: "{:.8f}".format(f) print n 

gives an error:

AttributeError: object 'module' has no attributes 'numbers'

How can I overcome this?

+5
source share
3 answers

This does what you need:

Code:

 from sympy.core.numbers import Float Float.__str__ = lambda f: "{:.8f}".format(float(f)) 

Test code:

 from sympy import N from sympy.core.numbers import Float f = 1.123456789 n = N(f, 8) Float.__str__ = lambda f: "{:.8f}".format(float(f)) print n 

Results:

 1.12345679 
+3
source

Monkeypatching __str__ is bad practice in this situation, since SymPy already has a built-in way to change the properties of SymPy objects by subclassing printers. Here I took and modified the original sympy.printing.str.StrPrinter._print_Float .

 from sympy.printing.str import StrPrinter class MyStrPrinter(StrPrinter) def _print_Float(self, expr): return '{:.8f}'.format(expr) 

Then use MyStrPrinter().doprint instead of str . You can also use str yourself using

 from sympy import init_printing init_printing(pretty_print=False, str_printer=MyStrPrinter().doprint) 
+1
source

Due to incorrect name selection, the submodule sympy.core.core imported through the "real" sympy.core , so trying to access sympy.core gets you sympy.core.core , and trying to access sympy.core.numbers gets you an AttributeError .

There are several ways you can get around this. SymPy provides access to the class you need, like sympy.Float , for example:

 import sympy do_whatever_with(sympy.Float) 
0
source

Source: https://habr.com/ru/post/1266566/


All Articles