Replies: 3 comments 2 replies
-
Or is the problem more subtle? Is it that in the |
Beta Was this translation helpful? Give feedback.
-
I found that explicit casting to def mystrip(x: T) -> T:
if isinstance(x, str):
return type(x)(x.strip())
return x Even though I wouldn't call this "idiomatic python", it seems to work. |
Beta Was this translation helpful? Give feedback.
-
In principle your annotated function is correct. This kind of narrowing seems safe to me, and I would consider this type of narrowing a desirable feature for type checkers, although I'm not sure how easy it would be to implement. It's possible that there are already issues open for the type checkers. If not, I'm sure that issues would be appreciated. In the meantime I would work around this using import typing
T = typing.TypeVar("T")
def mystrip(x: T) -> T:
if isinstance(x, str):
return typing.cast(T, x.strip())
return x |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Consider a function taking one parameter that always returns an object of the same type as its only parameter, e.g.,
While it is straight-forward to annotate the signature using a
TypeVar
, I see no way to make the typecheckers happy:mypy 1.9.0:
error: Incompatible return value type (got "str", expected "T") [return-value]
pyright 1.1.403:
Type "str" is not assignable to return type "T@mystrip"
I understand the problem that typecheckers are obviously not establishing a connection between the narrowing
x: str
that is used to compute the return type in the then branch and the restriction ofT
itself beingstr
in exactly this narrowing case.I believe that such defensive functions implementing a "perform certain type-preserving normalization on some values, return anything else unchanged" pattern is quite common in python. Ho do I annotate it to make the typecheckers happy? (apart from the trivial
# type: ignore
hack)Beta Was this translation helpful? Give feedback.
All reactions