File tree 1 file changed +48
-0
lines changed 1 file changed +48
-0
lines changed Original file line number Diff line number Diff line change @@ -762,6 +762,54 @@ aliases::
762
762
CompatReversible = Union[Reversible[T], SizedIterable[T]]
763
763
764
764
765
+ Modules as subtypes of protocols
766
+ --------------------------------
767
+
768
+ A module object is accepted where a protocol is expected if the public
769
+ interface of the given module is compatible with the expected protocol.
770
+ For example::
771
+
772
+ # file default_config.py
773
+ timeout = 100
774
+ one_flag = True
775
+ other_flag = False
776
+
777
+ # file main.py
778
+ import default_config
779
+ from typing import Protocol
780
+
781
+ class Options(Protocol):
782
+ timeout: int
783
+ one_flag: bool
784
+ other_flag: bool
785
+
786
+ def setup(options: Options) -> None:
787
+ ...
788
+
789
+ setup(default_config) # OK
790
+
791
+ To determine compatibility of module level functions, the ``self`` argument
792
+ of the corresponding protocol methods is dropped. For example::
793
+
794
+ # callbacks.py
795
+ def on_error(x: int) -> None:
796
+ ...
797
+ def on_success() -> None:
798
+ ...
799
+
800
+ # main.py
801
+ import callbacks
802
+ from typing import Protocol
803
+
804
+ class Reporter(Protocol):
805
+ def on_error(self, x: int) -> None:
806
+ ...
807
+ def on_success(self) -> None:
808
+ ...
809
+
810
+ rp: Reporter = callbacks # Passes type check
811
+
812
+
765
813
.. _discussion:
766
814
767
815
``@runtime_checkable`` decorator and narrowing types by ``isinstance()``
You can’t perform that action at this time.
0 commit comments