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 refer to the class-type ofself, without bound TypeVars?#2029

Unanswered
randolf-scholz asked this question inQ&A
Discussion options

Code sample inpyright playground

fromcollections.abcimportSequenceclassExpr:defsimplify(self)->"Expr": ...classExprSequence[E:Expr](Sequence[E],Expr):def__init__(self,exprs:list[E])->None: ...defsimplify(self)->Expr:returnself.__class__([e.simplify()foreinself])# ❌# "list[Expr]" cannot be assigned to list[E]

Inside a method likedef simplify(self), how can I refer to the runtime type oftype(self), i.e. the class ofself withoutE being already bound? Bothmypy andpyright infer bothtype(self) andself.__class__ essentially astype[typing.Self], which leads to the typing error in the example above.

I am not looking forExprSequence([e.simplify() for e in self]), because this has different runtime behavior.

You must be logged in to vote

Replies: 1 comment

Comment options

You can probably annotateself with eitherExprSequence[Expr] orExprSequence[Any] ifExprSequence is invariant inE.

You are giving up some type safety, especially in the latter case, but that already goes out of the window to some degree due to the implicit reliance onExprSequence.__init__ never violating LSP in a subclass. You could instead rely on an alternate constructor classmethod, which is checked for LSP violations, to improve safety.

You could even try to use a method-scopedTypeVar for this alternate constructor, so it can be bound independently of the class scopedE. Although that would make the constructor less convenient to use, since you can't useSelf as the return type in that case.

You must be logged in to vote
0 replies
Sign up for freeto join this conversation on GitHub. Already have an account?Sign in to comment
Category
Q&A
Labels
None yet
2 participants
@randolf-scholz@Daverball

[8]ページ先頭

©2009-2025 Movatter.jp