Defining a generic class, the doc below says the type argument can “usually” be inferred, which means not “always” so sometimes the type argument won’t be inferred:
When creating instances of generic classes, the type argument can usually be inferred.
class Box(Generic[T]):
def __init__(self, content: T) -> None:
self.content = content
Box(1) # OK, inferred type is Box[int]
Box[int](1) # Also OK
Box[int]('some string') # error: Argument 1 to "Box" has incompatible type "str"; expected "int"
So now, are there any cases which the type argument cannot be inferred?
Is the point of the docs, not that the type argument can always be inferred as object, but that if you write dynamic code such as below, then it’s not straightforward to infer T as a non-trivial type that’s useful to the user of the type system?
Any generic type without constructor fits the bill:
class Box[T]:
content: T
box = Box() # What's in the box??
There’s nothing wrong with this definition, yet T@Box cannot be inferred.
But in practice these usually come with some alternative way of constructing them, that does allow type-checkers to infer the generic type, for instance: