[Python-Dev] PEP 0484 - the Numeric Tower (original) (raw)

Oscar Benjamin oscar.j.benjamin at gmail.com
Wed Oct 14 17:21:30 EDT 2015


On Wed, 14 Oct 2015 21:57 Laura Creighton <lac at openend.se> wrote:

In a message of Wed, 14 Oct 2015 08:38:43 -0700, Guido van Rossum writes:

Perhaps you could solve this with type variables. Here's a little demonstration program: _ _from decimal import Decimal_ _from typing import TypeVar_ _F = TypeVar('F', float, Decimal)_ _def add(a: F, b: F) -> F:_ _return a+b_ _print(add(4.2, 3.14))_ _print(add(Decimal('4.2'), Decimal('3.14')))_ _print(add(Decimal('4.2'), 3.14))_ _ Note that the last line is invalid. mypy correctly finds this: _ _flt.py:8: error: Type argument 1 of "add" has incompatible value "object"_ _ (We could work on the error message.)

Now, I'm not sure that this is the best solution given the audience -- but the type variable 'F' only needs to be defined once, so this might actually work. -- --Guido van Rossum (python.org/~guido)

This looks good to me. I wonder if there is anything we can do, documentation and PEP wise to encourage people who write code to use it, rather than just using float?

It's not always appropriate though. If the author types it as float then they're obviously not thinking about decimal in which case it may not work correctly for decimal. Writing accurate numerical code that ducktypes with float and decimal is non-trivial even in cases where the operation is relatively trivial. Personally I just wouldn't mix them but if you want to see how tricky it can be take a look at statistics.sum.

Generally if it's possible to interchange floats and decimals in your code then there's probably no need for decimals in the first place. If mypy requires you to do an explicit conversion to float then there may be some seld-documenting merit in showing that conversion up front rather than assuming that it's okay to insert decimals where they're not expected. The point of static type checking is to detect precisely these kinds of errors.

-- Oscar -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-dev/attachments/20151014/666e380b/attachment-0001.html>



More information about the Python-Dev mailing list