This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author mark.dickinson
Recipients facundobatista, mark.dickinson, rhettinger, terry.reedy
Date 2008-10-09.13:39:41
SpamBayes Score 1.5042417e-10
Marked as misclassified No
Message-id <1223559584.24.0.470688627133.issue4087@psf.upfronthosting.co.za>
In-reply-to
Content
The Decimal module breaks transitivity of equality:  Decimal(2) == 2 and 
2 == float(2), but Decimal(2) != float(2).

The Python set and dict implementations rely on transitivity of equality 
for correct operation.

These two facts together give some strange results when playing with 
sets and dicts involving Decimals and floats.  For example (with Python 
2.6):

>>> s = set([Decimal(2), float(2)])
>>> t = set([2])
>>> s | t == t | s
False
>>> len(s | t)
2
>>> len(t | s)
1

Other strange examples, and possible solutions, were discussed recently 
on comp.lang.python;  see the thread starting at:

http://mail.python.org/pipermail/python-list/2008-September/508859.html

Possible solutions:

(1) Document the problem, making it clear in the language reference that 
correct set operation relies on transitivity of equality, and adding a 
note to the decimal documentation indicating that mixing floats and 
Decimals in a container is asking for trouble.

(2) Fix up Decimal so that equal numeric objects compare equal; this 
would also involve fixing the hash operation.  To me, this goes against 
the philosophy of keeping the Decimal module close to the specification.

(3) Terry Reedy suggested (in the c.l.python thread linked to above) a 
simpler version of (2): allow Decimal(i) == float(i) or Decimal(i) == 
Fraction(i) to return True for all integers i.  (Decimal('0.5') == 0.5 
would still return False.)  This fixes transitivity, and has the 
advantage of not requiring any changes to the hash functions:  
hash(Decimal(i)) == hash(float(i)) is already true for all integers i.

My own preference would be simply to document the problem;  it doesn't 
seem like something that's going to affect that vast majority of Python 
users.

Raymond, Facundo:  any thoughts?
History
Date User Action Args
2008-10-09 13:39:44mark.dickinsonsetrecipients: + mark.dickinson, rhettinger, terry.reedy, facundobatista
2008-10-09 13:39:44mark.dickinsonsetmessageid: <1223559584.24.0.470688627133.issue4087@psf.upfronthosting.co.za>
2008-10-09 13:39:43mark.dickinsonlinkissue4087 messages
2008-10-09 13:39:41mark.dickinsoncreate