Created
July 17, 2024 16:24
-
-
Save ridwanray/c7d567f5e0c7bbed3f8269abfe5a929a to your computer and use it in GitHub Desktop.
Guide for Python Type Annotation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| name : str = "Ray" | |
| """ | |
| age : int = 10 | |
| is_active : bool = True | |
| length : float = 2.2 | |
| size : bytes = b"test" | |
| """ | |
| """ | |
| #list | |
| names : list[str] = ["Ray", "Alex"] | |
| scores : list[int] = [1, 2, 3] | |
| #set | |
| values : set[int] = {6, 7} | |
| #dict | |
| user_info : dict[str, str] = { | |
| "name": "Ray", | |
| } | |
| #tuple | |
| items : tuple[str, int, float] = ("ray", 5, 2.5) | |
| """ | |
| """ | |
| # 3.8 and ealier | |
| from typing import List, Dict, Set, Tuple, Union | |
| names_2 : List[Union[str, int]] = ["Ray", "Alex"] | |
| values_2 : Set[int] = {6, 7} | |
| user_info_2 : Dict[str, str] = { | |
| "name": "Ray", | |
| } | |
| items_2 : Tuple[str, int, float] = ("ray", 5, 2.5) | |
| from typing import Iterator, Callable | |
| def infinite_gen(start:int) -> Iterator[int] : | |
| while start: | |
| yield start + 1 | |
| start +=1 | |
| gen = infinite_gen(2) | |
| def greet()->None: | |
| print("Hi") | |
| def say_hi(func: Callable[[] ,None])->None: | |
| func() | |
| """ | |
| """ | |
| from typing import ClassVar | |
| class Cat: | |
| group : ClassVar[str] = "Domestic" | |
| def __init__(self, name: str, age: int)-> None: | |
| self.name = name | |
| self.age = age | |
| def move(self)-> None: | |
| print(f"{self.name} is moving") | |
| cat1 = Cat("Name", 2) | |
| cat1.group = "New Group Name" | |
| """ | |
| # from typing import Final | |
| # BASE_URL : Final = "www.ridwanray.com" | |
| # BASE_URL = "google.com" | |
| from typing import final, Final | |
| from __future__ import annotations | |
| def send(src: Cat): | |
| ... | |
| class Cat: | |
| group = "Domestic" | |
| def __init__(self, name: str, age: int)-> None: | |
| self.name = name | |
| self.age = age | |
| @final | |
| def move(self)-> None: | |
| print(f"{self.name} is moving") | |
| # class MeowCat(Cat): | |
| # def move(self) -> None: | |
| # ... | |
| from collections.abc import Iterable, Mapping, MutableMapping | |
| def loop(items : Iterable[int]) -> None: | |
| for each in items: | |
| print(each) | |
| def update_dict(info: MutableMapping[str, str])-> None: | |
| info["name"] = "New Name" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment