Repository navigation
specialize generic subclass from inherited __init__ self annotation - #2389
crypt0lith wants to merge 1 commit into
Conversation
| # The ``self`` annotation should result in a type error | ||
| def __init__(self: "MyClass4[T2, T1]") -> None: ... | ||
|
|
||
| When the class being constructed is not explicitly specialized and inherits an |
There was a problem hiding this comment.
I think we should say explicitly that this solves only type arguments still undetermined after evaluating __new__. For example, suppose an invariant Base[T] defines __init__(self: Base[int]), and Child[T](Base[T]) defines __new__ to return Child[str]. The call Child() has no brackets, but its receiver is already specialized as Child[str] when we bind the inherited initializer. I’d expect the same binding error as for Child[str]().
| pass | ||
|
|
||
|
|
||
| assert_type(Class13(), Class13[int, str]) |
There was a problem hiding this comment.
Could we also check this through the accepts_callable helper in constructors_callable.py?
assert_type(accepts_callable(Class13)(), Class13[int, str])Both ty and Pyrefly are good on the direct call here, but infer Class12[int, str] after callable conversion. A caller passing a subclass as a factory should still get its subclass-specific methods on the result. It would help to say explicitly in the spec that the synthesized callable returns the specialized subclass.
|
|
||
|
|
||
| class Class12(Generic[T1, T2]): | ||
| def __init__(self: "Class12[int, str]") -> None: ... |
There was a problem hiding this comment.
Could we add a pair of calls that select different inherited __init__ overloads on the same subclass? The motivating Django field example has a null=False overload that leaves the defaults in place and a null=True overload whose annotated self makes the field nullable. Checking both results would cover overload selection and show that only the selected overload contributes its receiver constraints.
|
Thanks for the proposal and PR! I think this makes sense. |
discussion: https://discuss.python.org/t/proposal-specialize-generic-subclass-from-inherited-init-s-self-annotation/109979