Replies: 2 comments 2 replies
-
I tried a couple approaches and all look forbidden. The approach that's closest that I could imagine working would be this, class MyAnnotated:
def __class_getitem__(cls, key: tuple[type[T], Unpack[tuple[object, ...]]] | type[T]) -> T:
... Main issue is type checkers do not support custom class_getitem magic and I think this would likely require a pep (or some discussion at least). I think this could open some type level operators and that would be possible justification more then 1 argument Annotated. The current definition is very close to just having First operator that takes a tuple of types and returns First type. Similar trick could be used for taking callable and getting it's return type. Most languages lack type level operators although some functional ones have it (haskell and idris being two). Your use case that requires supporting both a type passed by itself + tuple[type, other stuff] is also awkward to express in type system. While possible it takes strange usage of variadic generics to do it. That part by itself, def f(x: tuple[type[T], Unpack[tuple[object, ...]]] | type[T]) -> T:
...
reveal_type(f(int)) # Shows int
reveal_type(f((int, "hello", 4.0))) # Shows int does work fine in pyright. Mypy gets first one right, but gives an error with second case (a bug to be filed). Mypy's PEP 646 implementation is still in progress. An alternative likely easier route is a feature request to allow normal Annotated to take just one argument. Then you could just do, if TYPE_CHECKING:
MyAnnotated = Annotated
else:
# Your implementation that adds metadata by default |
Beta Was this translation helpful? Give feedback.
-
@hmc-cs-mdrissi thank you
Yeah, I was looking into this - but then it gives another problem - annotated with default is not validating: do you see any way how to fool mypy/pylance into thinking that MyAnnotated is a special container that allows one or two arguments ? |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Hello
I'm bumping my head trying to develop a custom Annotated class...
Annotated allows to add some metadata to type hint that can be checked at runtime:
so metadata is always required - but I want to develop a similar type that initialises metadata with some default value:
I'm able to make it work with this code:
this works as expected - but VScode (pylance) does not understand it and cannot add autocompletion:
while works fine with default Annotated class:
is there a way to fool pylance somehow ?
The high level idea is to make some type container that allows to set default:
Beta Was this translation helpful? Give feedback.
All reactions