-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprotocol_typing.py
More file actions
40 lines (25 loc) · 888 Bytes
/
Copy pathprotocol_typing.py
File metadata and controls
40 lines (25 loc) · 888 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# protocol.py : use sample of Protocol from typing tools
# Even if this does not raise a runtime error,
# Mypy or any other type checker will raise an error if the type is not suitable when calling 'greet'.
# A way to pass it without inheriting from a common class is to use Protocol
from typing import Protocol
class Named(Protocol):
name: str
class Dog:
name = 'Good Dog'
class Cat:
name = 'Sweet Cat'
def greet_Named(obj : Named) -> None:
print(f"Hi {obj.name}")
def greet_Dog(obj : Dog) -> None:
print(f"Hi {obj.name}")
x = Dog()
greet_Named(x)
greet_Dog(x)
y = Cat()
greet_Named(y)
greet_Dog(y)
# The last line will raise an error when the previous won't
# > mypy .\protocol_typing.py
# protocol_typing.py:34: error: Argument 1 to "greet_Dog" has incompatible type "Cat"; expected "Dog" [arg-type]
# Found 1 error in 1 file (checked 1 source file)