-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path7_generic.py
More file actions
66 lines (49 loc) · 1.91 KB
/
7_generic.py
File metadata and controls
66 lines (49 loc) · 1.91 KB
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# A generic TypedDict can be created by inheriting from Generic with a list of type parameters:
from typing import TypedDict, Generic, TypeVar, ReadOnly
from typing import TypeVar, NewType
# without generic
def identity_without(x: int) -> int:
return x
# Define Generic type "T"
T = TypeVar("T")
def identity_with(x: T) -> T:
return x
print(identity_with("Simav")) # T is str type
print(identity_with(2)) # T is int type
# ---------------------------------------------------------------------------------
# Generic in TypedDict
T = TypeVar("T")
class Response(
TypedDict, Generic[T]
): # it is just a data shape not a class to inheritance from so we have a error
status: int
payload: T # This can be any type; it is generic see implementation below
# Response[T](TypedDict) is from python 3.12 and above
def func4(response: Response) -> None:
print(type(response))
# class call creation
response: Response = {"status": 200, "payload": "<html>blahh</html>"}
func4(response)# <class 'dict'>
# We have an error here why?
#because class GenProto try to inheritance Response but it's not a real class it just type
#annotation
class GenProto(Response[T]):
def meth(self) -> T:
pass
#see here if i try to instance from Response
response: Response = {"status": 200, "payload": "<html>blahh</html>"}
print(type(response))#it will be <class 'dict'>
#here we create a dict not an object like a real class
class GenProto2[T]:
def __init__(self, res: Response[T]) -> None:
self.res = res
def meth(self) -> T:
return self.res["payload"]
instance=GenProto2({"status": 200, "payload": "<html>blahh</html>"})
#see here if we have an instance from a real class
print(type(instance)) # <class '__main__.GenProto2'>
""""
Response looks like a class, but it is only used for static typing.
At runtime, it behaves like a dict,
so it cannot be used as a base class for inheritance with methods.
"""