0

To set a decimal precision I can write:

from decimal import Decimal,getcontext;
getcontext().prec = 20

and then use:

Decimal(some number)

Okay. But it is really tiresome to write Decimal every time, especially if you have many numbers to work with. How to set the python such that it always consider every number in a code with the specified number of decimal precision?

Jasen
  • 11,837
  • 2
  • 30
  • 48
Dileep
  • 45
  • 1
  • 4
  • 2
    Not possible. You can use a shorter name for `Decimal` if you want. – user2357112 Jul 08 '18 at 06:44
  • 3
    Also, if you're writing stuff like `Decimal(1.2)` in your code, that needs to be `Decimal('1.2')` to avoid `float` rounding error. – user2357112 Jul 08 '18 at 06:45
  • You _could_ write an import hook that turns all float literals into `Decimal` constructor calls instead (I think I even have one somewhere on my github), but you really shouldn't. Just `from decimal import Decimal as D`, or get your editor/IDE to help you with the repetition, or at most put all your module-level constants in one block of text and write code that `Decimal`-ifies all of them in one go, or something like that. – abarnert Jul 08 '18 at 07:48

1 Answers1

3

You really shouldn't. The difference between float and Decimal is very important, and you don't want to hide that difference from readers of your code.

If you're using a huge number of Decimal constants, some people like to do this:

from decimal import Decimal as D

c0 = D('273.15')
f0 = D('491.67')
c_ms = D('299792485')
# etc.

Another trick I've seen occasionally is to create a block of constants en masse:

constants = '''
   273.15 # c0
   491.67 # f0
   299792485 # c_ms
'''
constants = (line.split('#', 1)[0].strip() for line in constants.splitlines())
c0, f0, c_ms = (Decimal(line) for line in constants if line)

If you really want to push it, you can parse out the names and use globals()[name] to set them, but that's pretty icky.

If you want to go really over the top, you can write an import hook that changes every float literal into a Decimal constructor. This project is a starting point, although IIRC it only works in Python 3.3 to 3.5 or so out of the box.

But really, it's probably better to just get your editor or IDE to help you. That makes the code easier to write, without making it harder to read or misleading.

abarnert
  • 354,177
  • 51
  • 601
  • 671