-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample.py
More file actions
49 lines (30 loc) · 991 Bytes
/
Copy pathexample.py
File metadata and controls
49 lines (30 loc) · 991 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
41
42
43
44
45
46
47
48
49
"""Type hints examples — static typing in Python."""
from dataclasses import dataclass
from typing import Callable, Generic, Optional, TypeVar, Union
def greet(name: str, times: int = 1) -> str:
return (f"Hello, {name}! " * times).strip()
def process_items(items: list[int]) -> dict[str, int]:
return {"count": len(items), "sum": sum(items)}
@dataclass
class User:
id: int
name: str
email: Optional[str] = None
T = TypeVar("T")
class Box(Generic[T]):
def __init__(self, value: T):
self.value = value
def map(self, fn: Callable[[T], T]) -> "Box[T]":
return Box(fn(self.value))
def parse_id(value: Union[int, str]) -> int:
if isinstance(value, int):
return value
return int(value)
if __name__ == "__main__":
print(greet("Alice", 2))
print(process_items([1, 2, 3, 4]))
user = User(id=1, name="Bob")
print(user)
box = Box(10)
print(box.map(lambda x: x * 2).value)
print(parse_id("42"))