- Notifications
You must be signed in to change notification settings - Fork263
[V2] Annotating custom constructor methods for generic types.#2026
Unanswered
randolf-scholz asked this question inQ&A
Uh oh!
There was an error while loading.Please reload this page.
Uh oh!
There was an error while loading.Please reload this page.
-
Follow up to#2025. Consider this simple example. Is thereany way to annotate fromtypingimportAny,Self,assert_typeclassArray[T=Any]:@classmethoddeffrom_list(cls,x:list[T],/)->Self:returncls()assert_type(Array.from_list([]) ,Array[Any])assert_type(Array.from_list([1]) ,Array[int])assert_type(Array[int].from_list([]) ,Array[int])assert_type(Array[int].from_list([1]),Array[int]) I considered 5 different ways to implement it, including the use of metaclasses, but frustratingly,none of them make both MWE in playgroundCode sample inpyright playground # fmt: offfromtypingimportAny,Self,assert_typeclassArray1[T=Any]:@classmethoddeffrom_list(cls,x:list[T],/)->Self:returncls()assert_type(Array1.from_list([]) ,Array1[Any])assert_type(Array1.from_list([1]) ,Array1[int])# Error in pyrightassert_type(Array1[int].from_list([]) ,Array1[int])assert_type(Array1[int].from_list([1]),Array1[int])classArray2[T=Any]:@classmethoddeffrom_list(cls:"type[Array2[T]]",x:list[T],/)->"Array2[T]":returncls()assert_type(Array2.from_list([]) ,Array2[Any])assert_type(Array2.from_list([1]) ,Array2[int])# Error in pyrightassert_type(Array2[int].from_list([]) ,Array2[int])assert_type(Array2[int].from_list([1]),Array2[int])classArray3[T=Any]:@classmethoddeffrom_list[X=Any](cls:"type[Array3[X]]",x:list[X],/)->"Array3[X]":returncls()assert_type(Array3.from_list([]) ,Array3[Any])assert_type(Array3.from_list([1]) ,Array3[int])# Error in pyrightassert_type(Array3[int].from_list([]) ,Array3[int])assert_type(Array3[int].from_list([1]),Array3[int])classArray4Meta(type):deffrom_list[T=Any](cls,x:list[T],/)->"Array4[T]":returncls()classArray4[T](metaclass=Array4Meta): ...assert_type(Array4.from_list([]) ,Array4[Any])assert_type(Array4.from_list([1]) ,Array4[int])assert_type(Array4[int].from_list([]) ,Array4[int])# Error in mypy and pyrightassert_type(Array4[int].from_list([1]),Array4[int])classArray5Meta(type):deffrom_list[T=Any](cls:"type[Array5[T]]",x:list[T],/)->"Array5[T]":# error in mypy and pyrightreturncls()classArray5[T=Any](metaclass=Array5Meta): ...assert_type(Array5.from_list([]) ,Array5[Any])# Error in mypyassert_type(Array5.from_list([1]) ,Array5[int])# Error in mypy and pyrightassert_type(Array5[int].from_list([]) ,Array5[int])assert_type(Array5[int].from_list([1]),Array5[int]) |
BetaWas this translation helpful?Give feedback.
All reactions
Replies: 0 comments
Sign up for freeto join this conversation on GitHub. Already have an account?Sign in to comment