It would be beneficial for type annotations for parameters to which weak references are created to be limited to a protocol that requires conformant classes to have a weakref attribute that is an instance of weakref.ref.
Shouldn’t this be perfectly captured by a simple Protocol? I guess we can have that Protocol be predefined somewhere. I don’t think too much special support is needed, except that typecheckers should learn that __weakref__ is autogenerated for all object subclasses that don’t define __slots__.
Do you need something beyond what’s in the typeshed or has this covered everything?
This is a real gap in the type system that we can’t currently address cleanly. The stubs for the weakref module use an unbounded type parameter, implying that any type can be used with a weakref, but that is false; for example, weakref.ref(1) or weakref.ref(object()) fails. At runtime, this depends on whether there is a __weakref__ attribute on the class, but this attribute is synthesized by the interpreter under some circumstances. I haven’t fully worked out the rules for when it exists, but for instance it exists on user-defined subclasses of object, but not user-defined subclasses of int. We could come up with a list of rules for type checkers to infer whether something is weakrefable, plus a convention for marking weakrefability in stubs (not dissimilar to what we did in PEP 800 for disjoint bases).
Whether that’s worth it is a different question. It would add some complexity to type checkers, and this hasn’t come up as a common problem.
The latter is evidently the real difficulty.