Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

How to annotate the body of a single-parameter function whose return type equals type of parameter #2043

Answered by srittau
doeblerh asked this question in Q&A
Discussion options

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 x

While it is straight-forward to annotate the signature using a TypeVar, I see no way to make the typecheckers happy:

import typing
T = typing.TypeVar("T")
def mystrip(x: T) -> T:
 if isinstance(x, str):
 return x.strip()
 return x

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 of T itself being str 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)

You must be logged in to vote

You are right, this could actually be the problem. str.strip() is annotated to return str (or LiteralString) unconditionally, not Self.

Replies: 3 comments 2 replies

Comment options

Or is the problem more subtle? Is it that in the isinstance(x, str) case, T could be a non-trivial subclass of str? And therefore strip(), returning str itself and not T, indeed violates the signature annotation?

You must be logged in to vote
0 replies
Comment options

I found that explicit casting to T, i.e., constructing a T object from the result of x.strip() fixes the problem (for pyright at least).

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.

You must be logged in to vote
0 replies
Comment options

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 cast().

import typing
T = typing.TypeVar("T")
def mystrip(x: T) -> T:
 if isinstance(x, str):
 return typing.cast(T, x.strip())
 return x
You must be logged in to vote
2 replies
Comment options

What about subclasses of str (as previously mentioned by the OP)?

This code typechecks, but it fails at runtime (tested on CPython 3.12.11 and pyright playground):

from typing import cast, reveal_type
def mystrip[T](x: T) -> T:
 if isinstance(x, str):
 return cast(T, x.strip())
 return x
class Name(str):
 def greet(self) -> None:
 print(f"Hello, {self}!")
name = mystrip(Name(" World! "))
reveal_type(name) # pyright thinks it's `Name`, but CPython says it's a `str`
name.greet() # AttributeError!

Could this be a problem / soundness hole (introduced by the cast(...))?

Comment options

You are right, this could actually be the problem. str.strip() is annotated to return str (or LiteralString) unconditionally, not Self.

Answer selected by doeblerh
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet

AltStyle によって変換されたページ (->オリジナル) /