73_typing.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. from typing import Dict, Tuple, List
  2. bill: Dict[str, float] = {
  3. "apple": 3.14,
  4. "watermelon": 15.92,
  5. "pineapple": 6.53,
  6. }
  7. completed: Tuple[str] = ("DONE",)
  8. succeeded: Tuple[int, str] = (1, "SUCCESS")
  9. statuses: Tuple[str, ...] = (
  10. "DONE", "SUCCESS", "FAILED", "ERROR",
  11. )
  12. codes: List[int] = (0, 1, -1, -2)
  13. from typing import Union
  14. def resp200(meaningful) -> Union[int, str]:
  15. return "OK" if meaningful else 200
  16. from typing import Self
  17. class Employee:
  18. name: str = "John Doe"
  19. age: int = 0
  20. def set_name(self: Self, name) -> Self:
  21. self.name = name
  22. return self
  23. from typing import TypeVar, Type
  24. T = TypeVar("T")
  25. # "mapper" is a type, like int, str, MyClass and so on.
  26. # "default" is an instance of type T, such as 314, "string", MyClass() and so on.
  27. # returned is an instance of type T too.
  28. def converter(raw, mapper: Type[T] = None, default: T = None) -> T:
  29. try:
  30. return mapper(raw)
  31. except:
  32. return default
  33. raw: str = '4'
  34. result: int = converter(raw, mapper=int, default=0)
  35. from typing import TypeVar, Callable, Any
  36. T = TypeVar("T")
  37. def converter(raw, mapper: Callable[[Any], T] = None, default: T = None) -> T:
  38. try:
  39. return mapper(raw)
  40. except:
  41. return default
  42. # Callable[[Any], ReturnType] means a function declare like:
  43. # def func(arg: Any) -> ReturnType:
  44. # pass
  45. # Callable[[str, int], ReturnType] means a function declare like:
  46. # def func(string: str, times: int) -> ReturnType:
  47. # pass
  48. # Callable[..., ReturnType] means a function declare like:
  49. # def func(*args, **kwargs) -> ReturnType:
  50. # pass
  51. def is_success(value) -> bool:
  52. return value in (0, "OK", True, "success")
  53. resp = {'code': 0, 'message': 'OK', 'data': []}
  54. successed: bool = converter(resp['message'], mapper=is_success, default=False)
  55. class A:
  56. x: List[Callable[[int], Any]]
  57. y: Dict[str, int]
  58. a = A()
  59. assert not hasattr(a, 'x')
  60. assert not hasattr(a, 'y')
  61. class B:
  62. x: List[Callable[[int], Any]] = []
  63. y: Dict[str, int] = {}
  64. b = B()
  65. assert hasattr(b, 'x')
  66. assert hasattr(b, 'y')
  67. abc123: int
  68. assert 'abc123' not in globals()