@@ -352,6 +352,53 @@ the parameters are positional-only. Example (using the legacy syntax for generic
352352 copy_a = copy_b # OK
353353 copy_b = copy_a # Also OK
354354
355+ Binding of types in protocol attributes
356+ ***************************************
357+
358+ All protocol attributes annotations are treated as externally visible types
359+ of those attributes. This means that for example callables are not bound,
360+ and descriptors are not invoked:
361+
362+ .. code-block :: python
363+
364+ from typing import Callable, Protocol, overload
365+
366+ class Integer :
367+ @overload
368+ def __get__ (self , instance : None , owner : object ) -> Integer: ...
369+ @overload
370+ def __get__ (self , instance : object , owner : object ) -> int : ...
371+ # <some implementation>
372+
373+ class Example (Protocol ):
374+ foo: Callable[[object ], int ]
375+ bar: Integer
376+
377+ ex: Example
378+ reveal_type(ex.foo) # Revealed type is Callable[[object], int]
379+ reveal_type(ex.bar) # Revealed type is Integer
380+
381+ In other words, protocol attribute types are handled as they would appear in a
382+ ``self `` attribute annotation in a regular class. If you want some protocol
383+ attributes to be handled as though they were defined at class level, you should
384+ declare them explicitly using ``ClassVar[...] ``. Continuing previous example:
385+
386+ .. code-block :: python
387+
388+ from typing import ClassVar
389+
390+ class OtherExample (Protocol ):
391+ # This style is *not recommended*, but may be needed to reuse
392+ # some complex callable types. Otherwise use regular methods.
393+ foo: ClassVar[Callable[[object ], int ]]
394+ # This may be needed to mimic descriptor access on Type[...] types,
395+ # otherwise use a plain "bar: int" style.
396+ bar: ClassVar[Integer]
397+
398+ ex2: OtherExample
399+ reveal_type(ex2.foo) # Revealed type is Callable[[], int]
400+ reveal_type(ex2.bar) # Revealed type is int
401+
355402 .. _predefined_protocols_reference :
356403
357404Predefined protocol reference
0 commit comments