Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Sign up for free
Menu
Search
Features
All features
Private URLs
Password Protection
Custom URLS
Scheduled publishing
Remove Branding
Restrict embedding
Deck Collections
Notes
Features
All features
Private URLs
Password Protection
Custom URLS
Scheduled publishing
Remove Branding
Restrict embedding
Deck Collections
Notes
Explore
Featured decks
Featured speakers
Programming
Technology
Storyboards
Explore
Featured decks
Featured speakers
Programming
Technology
Storyboards
Pricing
Search
Sign in
Sign up for free
Python 3.13で進化したtype predicateについてと、タグ付きユニオンを使っ...
Search
nsuz
December 22, 2024
Programming
390
0
Share
Embed
Copy iframe code
Copy JS code
Copy link
Start on current slide
Python 3.13で進化したtype predicateについてと、タグ付きユニオンを使ったtype narrowingについて
Python札幌 シーズンX Vol.3 LT勉強会
発表資料
nsuz
December 22, 2024
Transcript
17 slides
Python 3.13で進化したtype predicateについてと、タ グ付きユニオンを使ったtype narrowingについて 鈴木直柔 2024-12-23 Python札幌
自己紹介 鈴木直柔 (@nsuz) 株式会社 エクサウィザーズ ソフトウェアエンジニア
Python 3.13で進化したtype predicate
a: list[str | None] = ["foo", None, "bar", None, "baz"]
b = filter(lambda x: x is not None, a) c = map(lambda x: x.upper(), b)
None
type predicete function def is_not_none[T](x: T | None) -> TypeIs[T]:
return x is not None typing.TypeIs Python 3.13で追加された。TypeGuard(3.10~)の進化版。
None
TypeGuardから進化したポイント TypeGuardの課題
TypeGuardから進化したポイント TypeIs 型述語関数の返り値がTrueのとき、元の変数の型との交差型として推論されるよ うになった 型述語関数の返り値がFalseのときもnarrowingできるようになった
タグ付きユニオンを使ったtype narrowing
class Ok[T](TypedDict): type: Literal["ok"] value: T class Error(TypedDict): type: Literal["error"]
value: Exception type Result[T] = Ok[T] | Error def unwrap[T](result: Result[T]) -> T: if result["type"] == "ok": return result["value"] # result: Ok[T] else: raise result["value"] # result: Error
data: list[Result[int]] = [ {"type": "ok", "value": 42}, {"type": "error",
"value": ValueError("Something went wrong")}, ] for d in data: try: print(unwrap(d)) except Exception as e: print(f"Error!!!! {e}")
例えば・・・ APIレスポンスが、 成功時 { "result": 0, "data": ... } 失敗時
{ "result": 1, "error": ... } みたいなとき
from typing import Literal, TypedDict type Data = list[str] class
OkResponse(TypedDict): result: Literal[0] data: Data class ErrorResponse(TypedDict): result: Literal[1] error: str type Response = OkResponse | ErrorResponse def unwrap[T](res: Response) -> Data: if res["result"] == 0: return res["data"] else: raise Exception(res["error"]) data: list[Response] = [ {"result": 0, "data": ["foo", "bar", "baz"]}, {"result": 1, "error": "ERROR_CODE_123"}, ] for d in data: try: print(unwrap(d)) except Exception as e: print(f"Error!!!! {e}")
(ただ、Pythonの場合、内部でつくるデータについてはTypedDictでタグ付きユニオン をつくるよりも、dataclassなどでクラスにした方が、構造的パターンマッチングでス マートに扱えるかも・・?)
from dataclasses import dataclass @dataclass class Ok[T]: value: T @dataclass
class Error: value: Exception type Result[T] = Ok[T] | Error def unwrap[T](result: Result[T]) -> T: match result: case Ok(v): return v case Error(e): raise e
data: list[Result[int]] = [ Ok(42), Error(ValueError("Something went wrong")), ] for
d in data: try: print(unwrap(d)) except Exception as e: print(f"Error!!!! {e}")
More Decks by nsuz
See All by nsuz
「無ければ作る」Backlogに欲しい機能を自分で作った話
nsuz
0
1.7k
Other Decks in Programming
See All in Programming
우리의 Nitro Modules는 당신의 Turbo Modules보다 아름답다
l2hyunwoo
0
260
AIが実装を担う時代の「技術設計」と「チームマネジメント」
kamina_zzz
2
270
Growing PicoRuby's Ecosystem on ESP32
yuuu
2
140
社内AIエージェント「Askワンバン」における コストチューニングの取り組み
t0yohei
0
170
Vapor Mode でアクセシビリティは 壊れないか検証した話
fuqda
1
350
AI時代のFlutter品質設計 — アプリ品質を守るQuality Layers
omatty198
0
380
なぜ私たちは「現時点では」KMPの導入を見送ったのか
chigichan24
1
280
Crash Auto Pipelines
veronikapj
1
420
将来の標準フォーマッター?ktfmtを深堀る
t45k
0
170
小さなアプリを作って公開するまで
onozaty
0
190
AIが生成したコードは読むべきか?抽象化設計とコードの品質保証 / abstraction-design-and-quality
minodriven
16
9.2k
React Native経験者が Flutterを30⽇間触って驚いたこと
3saito
0
190
Featured
See All Featured
Templates, Plugins, & Blocks: Oh My! Creating the theme that thinks of everything
marktimemedia
31
3k
Site-Speed That Sticks
csswizardry
13
1.6k
The #1 spot is gone: here's how to win anyway
tamaranovitovic
4
1.2k
Balancing Empowerment & Direction
lara
6
1.4k
Product Roadmaps are Hard
iamctodd
55
13k
Game over? The fight for quality and originality in the time of robots
wayneb77
1
330
HU Berlin: Industrial-Strength Natural Language Processing with spaCy and Prodigy
inesmontani
PRO
0
810
Mind Mapping
helmedeiros
1
440
Marketing Yourself as an Engineer | Alaka | Gurzu
gurzu
0
370
Accessibility Awareness
sabderemane
1
300
The Web Performance Landscape in 2024 [PerfNow 2024]
tammyeverts
12
1.4k
Leveraging Curiosity to Care for An Aging Population
cassininazir
1
570