Title is pretty self explanatory.
Minimal reproducible code:
import numpy
mean_sex: float = numpy.mean([1, 2, 3])
print(mean_sex)
print(type(mean_sex))
Output is:
001 | 2.0
002 | <class 'numpy.float64'>
I'm using: PyCharm 2022.2 (Community Edition) Build #PC-222.3345.131, built on July 27, 2022 Runtime version: 17.0.3 7-b469.32 amd64 VM: OpenJDK 64-Bit Server VM by JetBrains s.r.o. Windows 11 10.0 GC: G1 Young Generation, G1 Old Generation Memory: 2030M Cores: 16 Non-Bundled Plugins: com.chesterccw.excelreader (2022.2.1)
CodePudding user response:
numpy.mean()
can return several types (the return type is Any
) and what is actually returned depends on the arguments to the function.
This is fairly typical in Python, since it is a dynamically typed language - there are no hard restrictions on what type a function returns and hinting can only get you so far.
In this case, what type is returned depends on the value of parameters like axis
, which could cause the function to return a numpy.ndarray
instead of a numpy.float64
. Since you made it clear that you want mean_sex
to explicitly contain a float
, that causes the type hint you shared.
The solution is to make sure that the value coming out of numpy.mean()
is actually a float
, for example by passing it to float()
:
mean_sex: float = float(numpy.mean([1, 2, 3]))
The question here is "why bother?" You could just as easily do:
mean_sex = numpy.mean([1, 2, 3])
Is there a reason you want to specify the type for mean_sex
?