๐Ÿšฉ

Migrating to Python 3.10

ย 
ย 

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
ย