Repository navigation
How to make an unspecialized generic default to Any in strict mode?
#11108
Unanswered
Graham Preston (grahamcracker1234)
asked this question in
Q&A
Replies: 1 comment 1 reply
|
If you want to deliberately treat the contents of any from typing import Any, Generic, TypeGuard, TypeVar
T = TypeVar("T")
class Foo(Generic[T]):
def __init__(self, bar: T):
self.bar = bar
def is_foo(value: object) -> TypeGuard[Foo[Any]]:
return isinstance(value, Foo)
def match_foo(obj: Any) -> Foo[Any] | None:
match obj:
case _ if is_foo(obj):
return obj
case _:
return None
assert match_foo(Foo(3)) is not None
assert match_foo("not a Foo") is NoneI checked this with Pyright 1.1.414 in strict mode and Python 3.12.14. It produces no partially-unknown diagnostics and returns the original This is an explicit decision to erase the element type, so it doesn't establish that |
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
I’m trying to figure out how to tell pyright (in strict mode) that a bare instantiation of a generic class should resolve to
Foo[Any]rather than a partially unknown `Foo[Unknown].Here’s the minimal scenario:
In strict mode, pyright reports that
foois of typeFoo[Unknown]rather than resolving it toFoo[Any].What I would like
I would like pyright to interpret a bare pattern match on
Foo()as meaningFoo[Any]. That is, if type parameters cannot be inferred during pattern matching, default them toAnyrather than leaving them as partially unknown.I tried adding type constraints and a default type to the generic type in the
Fooclass, but it doesn't seem to do anything.Ideally whatever strategy is used here could also be used for built-in collection types and
collections.abc.Questions
Is there any supported way in pyright strict mode to make unspecialized generics default to
Any?Is there a configuration option, typing trick, or pattern-match protocol hook that ensures that a bare
Foo()match results in a concreteFoo[Any]instead of a partially‑inferred generic?If the answer is “no, pyright intentionally preserves unspecialized generic parameters,” why is that? And what is the recommended idiom? For example:
…but I’m wondering whether pyright has an officially encouraged way of handling pattern‑matching with generic types when the type parameter cannot be inferred.
All reactions