PyCharm (Python version 3.11.3 on Windows) is flagging Expected type 'int', got 'float' instead
where I use random.randint(x/y, 10)
(where x/y will be, say, 5.0), which makes sense. However the code still runs.
Someone else using a different IDE tried to run the code and TypeError
prevented the code from running. I don't know what system/version that was on, but it doesn't make sense to me.
For minimal viable program:
import random
x = 10
y = 2
print(random.randint(x/y, 10)
Why is there a discrepancy between the PyCharm warning and the runtime errors, and why is it not consistent across systems?
The warnings/errors that PyCharm gives are the result of static analysis based on type hints and can in principle be different from the runtime behaviour.
In the case of random.randint
, prior to Python 3.12, it accepted integer-value float
arguments and converted them to int
implicitly.
Since Python 3.12, float
arguments are no longer allowed at all, see https://docs.python.org/3/library/random.html#random.randrange (randint
delegates to randrange
).
So, two things could have caused a TypeError
:
x/y
was not an exact integer value (e.g. 0.3/0.1
is mathematically 3 but in floating-point arithmetic slightly smaller than 3).