Movatterモバイル変換


[0]ホーム

URL:


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

Unanswered
doeblerh asked this question inQ&A
Discussion options

Consider a function taking one parameter that always returns an object of the same type as its only parameter, e.g.,

defmystrip(x):ifisinstance(x,str):returnx.strip()returnx

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

importtypingT=typing.TypeVar("T")defmystrip(x:T)->T:ifisinstance(x,str):returnx.strip()returnx

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 narrowingx: 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)

You must be logged in to vote

Replies: 3 comments 2 replies

Comment options

Or is the problem more subtle? Is it that in theisinstance(x, str) case,T could be a non-trivial subclass of str? And thereforestrip(), returningstr itself and notT, indeed violates the signature annotation?

You must be logged in to vote
0 replies
Comment options

I found that explicit casting toT, i.e., constructing aT object from the result ofx.strip() fixes the problem (for pyright at least).

defmystrip(x:T)->T:ifisinstance(x,str):returntype(x)(x.strip())returnx

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

importtypingT=typing.TypeVar("T")defmystrip(x:T)->T:ifisinstance(x,str):returntyping.cast(T,x.strip())returnx
You must be logged in to vote
2 replies
@RBerga06
Comment options

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

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

fromtypingimportcast,reveal_typedefmystrip[T](x:T)->T:ifisinstance(x,str):returncast(T,x.strip())returnxclassName(str):defgreet(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 thecast(...))?

@srittau
Comment options

You are right, this could actually be the problem.str.strip() is annotated to returnstr (orLiteralString) unconditionally, notSelf.

Sign up for freeto join this conversation on GitHub. Already have an account?Sign in to comment
Category
Q&A
Labels
None yet
3 participants
@doeblerh@srittau@RBerga06

[8]ページ先頭

©2009-2025 Movatter.jp