ย
ย
Match
๋จ์ํ switch ๋ฌธ์ด ํ์ด์ฌ์์ ์๊ฒผ๋ค๊ณ ์๊ฐ ํ ์๋ ์์ง๋ง ์ฝ๋๋ฅผ ๋ ๊ฐ๊ฒฐํ๊ฒ๋ ์ธ ์ ์๋ค.
If x is tuple
if isinstance(x, tuple) and len(x) == 2: host, port = x mode = "http" elif isinstance(x, tuple) and len(x) == 3: host, port, mode = x # Etc.
Code like this is more elegantly rendered usingย
match:match x: case host, port: mode = "http" case host, port, mode: pass # Etc.
์๋ x๊ฐ tuple์ธ์ง๋ ์ฒดํฌํด์ผํ์ผ๋ host, port๋ก ๋๋ ์ง๋ค๋ ๊ฒ์ผ๋ก tuple์ธ์ง ์ฒดํฌ๊ฐ ๊ฐ๋ฅํ๊ณ tuple์ item์ด 2๊ฐ๋ผ๋ ์๋ฏธ์ด๊ธฐ๋ ํ๋ค.
ย
If x is JSON
Example JSON)
{ "type": "cat", "name": "Cat name 1", "pattern": "Pattern 1" }
{ "type": "dog", "name": "Dog name 1", "breed": "Breed 1" }
ย
match json_pet: case {"type": "cat", "name": name, "pattern": pattern}: return Cat(name, pattern) case {"type": "dog", "name": name, "breed": breed}: return Dog(name, breed) case _: raise ValueError("Not a suitable pet")
ย
ย
ย
Parameter typing
๋ฐ์ฝ๋ ์ดํฐ๋ฅผ ์ฐ์ง ์๋๋ผ๋ ์ฌ์ฉํ๋ ๋ผ์ด๋ธ๋ฌ๋ฆฌ๊ฐ ์ ์ฉํ๋ค๋ฉด ํ์
์ฒดํฌ์์ ์๊ฑธ๋ฆฌ๋๊ฒ์ด ์ถ๊ฐ์ ์ผ๋ก ๊ฑธ๋ฆด ์ ์์๋ฏ?
ย
ย
ย
from typing import Awaitable, Callable, TypeVar R = TypeVar("R") def add_logging(f: Callable[..., R]) -> Callable[..., Awaitable[R]]: async def inner(*args: object, **kwargs: object) -> R: await log_to_database() return f(*args, **kwargs) return inner @add_logging def takes_int_str(x: int, y: str) -> int: return x + 7 await takes_int_str(1, "A") await takes_int_str("B", 2) # fails at runtime
ย