-
The following code produces a import numpy as np
from typing import Any, TypeVar
T = TypeVar('T', bound=np.floating[Any])
def f(x: T) -> T:
return x**2 The solution is to cast the result of However, I was expecting that pylance would infer that Is this behavior expected? Is there an anything I can do to avoid the explicit cast? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 4 replies
-
Yes, this behavior is expected. Pyright (the type checker that pylance is based on) is not using inference in this case. It's applying type evaluation rules dictated by the Python typing spec and the type information provided by the numpy library. The numpy library indicates that the |
Beta Was this translation helpful? Give feedback.
As I said above, there is no inference going on here. Pyright is simply applying standard type evaluation rules. There's nothing to "address" here because pyright is behaving correctly as a static type checker. If we were to change its behavior as you're suggesting, it would no longer be compliant with the Python typing spec, and it wouldn't correctly reflect what happens at runtime.
Let's take a closer look at the example above where you're using multiplication with a value whose type is described by a type variable with an upper bound of
float
. The*
operator invokes thefloat.__mul__
method. The type information for this method can be found in thebuiltins.pyi
type stub file, part of t…