Engineering numerical format PEP discussion

Stefan Krah stefan-usenet at bytereef.org
Mon Apr 26 11:33:37 CEST 2010


Keith <keith.brafford at gmail.com> wrote:
> Even though this uses the to_eng_string() function, and even though I
> am using the decimal.Context class:
> 
> >>> c = decimal.Context(prec=5)
> >>> decimal.Decimal(1234567).to_eng_string(c)
> '1234567'
> 
> That is not an engineering notation string.

To clarify further: The spec says that the printing functions are not
context sensitive, so to_eng_string does not *apply* the context.

The context is only passed in for the 'capitals' value, which determines
whether the exponent letter is printed in lower or upper case.


This is one of the unfortunate situations where passing a context can
create great confusion for the user. Another one is:


>>> c = Context(prec=5)
>>> Decimal(12345678, c)
Decimal('12345678')


Here the context is passed only for the 'flags' and 'traps' members:

>>> Decimal("wrong", c)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.2/decimal.py", line 548, in __new__
    "Invalid literal for Decimal: %r" % value)
  File "/usr/lib/python3.2/decimal.py", line 3836, in _raise_error
    raise error(explanation)
decimal.InvalidOperation: Invalid literal for Decimal: 'wrong'


>>>c.traps[InvalidOperation] = False
>>> Decimal("wrong", c)
Decimal('NaN')


Stefan Krah






More information about the Python-list mailing list