[issue47234] PEP-484 "numeric tower" approach makes it hard/impossible to specify contracts in documentation

Jelle Zijlstra report at bugs.python.org
Tue Apr 5 16:52:43 EDT 2022


Jelle Zijlstra <jelle.zijlstra at gmail.com> added the comment:

Thanks for your report, but I would appreciate a more concise explanation. Let me try to rephrase the problem.

Given this function:

def mean(x: list[float]) -> float:
    return sum(x) / len(x)

We want to provide a guarantee that if x is a nonempty list containing only floats, the function returns successfully and returns a float.

But the type system currently doesn't give this guarantee, because PEP 484 specifies that ints are compatible with floats, and `mean([0.0, 1.25, 10**1000, 0.0])` will throw OverflowError.

---

We generally discuss issues with the general type system over at https://github.com/python/typing/issues, but here are a few thoughts:

- The type system doesn't generally try to cover exceptions. Your function could also raise MemoryError, or KeyboardInterrupt, and the type system can't tell you.
- The concrete proposal here would be to make int no longer implicitly compatible with float. That might be nice, but at this point it would be a big break in backwards compatibility, so I'm not sure we can do it.

----------
nosy: +AlexWaygood, JelleZijlstra, gvanrossum, kj

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue47234>
_______________________________________


More information about the Python-bugs-list mailing list