Question

I've found a strange behavior in the decimal module. The "signature" of the class Decimal is:

Decimal(value='0', context=None)

So, I supposed that I can do something like:Decimal('3', None). But this code raises a TypeError exception in python3.3 but not in python2.7.

In my investigations, I tried debugging with pdb:pdb.set_trace("Decimal('3', None)"), but nothing happened! As soon as I type s the same exception is raised.

Can someone explain the reasons of these behaviors?

Was it helpful?

Solution

I can confirm the behaviour for Python 3.3. It somehow detects that you passed the None as the context and it does not like it (even though it is documented as the default value).

Python 3.3.0 (v3.3.0:bd8afb90ebf2, Sep 29 2012, 10:57:17) [MSC v.1600 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import decimal
>>> decimal.Decimal('3', None)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: optional argument must be a context
>>> decimal.Decimal('3')
Decimal('3')

Update: But it works with 3.2.3

Python 3.2.3 (default, Apr 11 2012, 07:12:16) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import decimal
>>> decimal.Decimal('3', None)
Decimal('3')
>>>

Update: The reason can be found in the doc...

What’s New In Python 3.3 says:

decimal

issue 7652 - integrate fast native decimal arithmetic. C-module and libmpdec written by Stefan Krah.

When comparing the decimal.py files, they may look the same at first, but the Python 3.3 version contains the following code almost at the end:

try:
    import _decimal
except ImportError:
    pass
else:
    s1 = set(dir())
    s2 = set(dir(_decimal))
    for name in s1 - s2:
        del globals()[name]
    del s1, s2, name
    from _decimal import *

... while the older Python 3.2 does not. It says that if the binary _decimal implementation could be imported, the older implementation from decimal.py is ignored. And the binary module cannot be debugged using the Python-code debugger.

The question is whether the observed behaviour should not be considered a bug.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top