-
|
Consider a function taking one parameter that always returns an object of the same type as its only parameter, e.g., def mystrip(x):
if isinstance(x, str):
return x.strip()
return xWhile it is straight-forward to annotate the signature using a import typing
T = typing.TypeVar("T")
def mystrip(x: T) -> T:
if isinstance(x, str):
return x.strip()
return xmypy 1.9.0: I understand the problem that typecheckers are obviously not establishing a connection between the narrowing 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 |
Beta Was this translation helpful? Give feedback.
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 xEven 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.
You are right, this could actually be the problem.
str.strip()is annotated to returnstr(orLiteralString) unconditionally, notSelf.