Skip to content Skip to sidebar Skip to footer

Python Decimal Not Accepting Getcontext() Precision Modifications

Just trying the basic python Decimal module and it seems to not work (in jupyter notebook): from decimal import * getcontext().prec = 1 getcontext() return Context(prec=28, round

Solution 1:

It looks like a bug.

Update: This should be fixed in ipython 6.0+, which was released in April 2021. Here's the specific PR for the fix: https://github.com/ipython/ipykernel/pull/632

If you are checking your installed versions with pip or jupyter --version, the specific library you are looking for is ipykernel >= 6.0

*EDIT: Behavior seems to vary depending on versions. The most reliable workaround should be to define decimal precision within each cell where you need it to apply, or to move precision definitions to external modules.

I've done some troubleshooting and here's what I found*:

  • If you have just started Jupyter, getcontext().prec = x behaves normally.
  • If you use Run > "Run All Cells", behavior is also normal.
  • If you restart the kernel within the Jupyter UI, precision resets to 28 between manual cell executions.

I've filed a bug with Jupyter - https://github.com/jupyter/notebook/issues/5260

As an easy but kind of ugly workaround, defining getcontext().prec = 1 in each cell where you want that precision applied appears to force Jupyter to use that.

Or - this is quite strange - running this command in any cell appears to fix precision for the entire notebook after it is run. Put it at the top of your nb and you should be good:

!jupyter notebook --version

Finally, imported modules should behave normally. If you go that route, I might suggest using something like the 'nbdev' package to streamline the process of creating modules from notebooks - it makes it a lot easier to keep organized than copy/pasting from notebooks.

Post a Comment for "Python Decimal Not Accepting Getcontext() Precision Modifications"