2

当我在不同的 Python 版本(2.5 与 2.6)和不同的平台(FreeBSD 与 Mac OS)上运行 doctests 时,字符串的引用方式不同:

Failed example:
    decode('{"created_by":"test","guid":123,"num":5.00}')
Expected:
    {'guid': 123, 'num': Decimal("5.00"), 'created_by': 'test'}
Got:
    {'guid': 123, 'num': Decimal('5.00'), 'created_by': 'test'}

因此,在一个盒子上,repr(decimal.Decimal('5.00')) 会导致“Decimal(“5.00”)”,而另一个盒子会导致“Decimal('5.00')”。有没有办法在不创建更复杂的测试逻辑的情况下解决这个问题?

4

2 回答 2

4

这实际上是因为decimal模块的源代码发生了变化: 在 python 2.4 和 python2.5 中,decimal.Decimal.__repr__函数包含:

return 'Decimal("%s")' % str(self)

而在python2.6中它包含:

return "Decimal('%s')" % str(self)

所以在这种情况下,最好的办法就是打印出str()结果并在必要时单独检查类型......

于 2009-08-10T10:49:29.683 回答
0

在 D avid Fraser的热门歌曲之后,我在 Python 邮件列表中找到了 Raymond Hettinger 的这个建议

我现在使用这样的东西:

import sys
if sys.version_info[:2] <= (2, 5):
    # ugly monkeypatch to make doctests work. For the reasons see
    # See http://mail.python.org/pipermail/python-dev/2008-July/081420.html
    # It can go away once all our boxes run python > 2.5
    decimal.Decimal.__repr__ = lambda s: "Decimal('%s')" % str(s)
于 2009-08-10T11:51:13.273 回答