"numbers.Real" makes it really hard to work with typechecking
See original GitHub issueDescribe the bug
When working with mypy
arguments of type numbers.Real
cannot accept regular float
or int
values. Making working with them very unproductive due to having to typing.cast(numbers.Real, value)
all over the code.
To Reproduce Run mypy on this file for example:
import numbers
import typing
import mip
model = mip.Model("Model")
x = 1
model.add_var("var1", lb=x) # "Literal[1]" is incompatible with "Real"
y = 1.0
model.add_var("var2", lb=y) # "float" is incompatible with "Real"
z: numbers.Real = 5.6 # "float" is incompatible with "Real"
model.add_var("var3", lb=z)
z = typing.cast(numbers.Real, 7.8) # have to do this everytime
model.add_var("var4", lb=z) # no problem
Edit 1: Additional steps are needed to generate the stub for the library.
export MYPYPATH=./out
stubgen -p mip
mypy main.py
Expected behavior
I understan reasoning for using number.Real
however even the PEP 484 suggests using float instead:
Rather than requiring that users write import numbers and then use numbers.Float etc., this PEP proposes a straightforward shortcut that is almost as effective: when an argument is annotated as having type float, an argument of type int is acceptable; similar, for an argument annotated as having type complex, arguments of type float or int are acceptable. This does not handle classes implementing the corresponding ABCs or the fractions.Fraction class, but we believe those use cases are exceedingly rare.
Desktop (please complete the following information):
- Operating System, version: Windows 10 64bit
- Python version: 3.9
- Python-MIP version (we recommend you to test with the latest version): 1.13
Additional context I know this isn’t a proper bug, however it has been very frustrating to work with.
Issue Analytics
- State:
- Created 3 years ago
- Reactions:2
- Comments:5 (2 by maintainers)
I am going to add mypy to CI. See #270. There I started to refactor the numbers.Real for typing to make it mypy compatible.
I don’t know if you saw, but I pulled out a lot of my own number typing work-arounds into their own package called
numerary
. If this journey lines up with your own,numerary
could be an intermediary solution until python/mypy#3186 is fixed. (Alternatively, the techniques used therein might provide inspiration if you can’t take a dependency.) Happy to consult here, if helpful. Apologies if this is a distraction.