Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
Python 3.13で進化したtype predicateについてと、タグ付きユニオンを使っ...
Search
nsuz
December 22, 2024
Programming
340
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
More Decks by nsuz
See All by nsuz
「無ければ作る」Backlogに欲しい機能を自分で作った話
nsuz
0
1.7k
Other Decks in Programming
See All in Programming
Generative UI & AI-Assistants for Your Angular Solutions
manfredsteyer
PRO
0
110
AI時代、エンジニアはどう育つのか -未経験エンジニアの成長を間近で見て考えたこと-
thasu0123
0
110
AWS CDK を「作」ってみた 〜フルスクラッチで見えた CDK の裏側〜 / aws-cdk-from-scratch
gotok365
3
320
Prismを使った型安全な暗号化_関数型まつり2026
_fhhmm
0
130
型も通る、synthも通る、それでも危ない 〜AIのCDKの権限とコストを機械で検証する〜 / It Passes Type Checks, It Passes Synth Checks, but It’s Still Risky — Automatically Verifying Permissions and Costs in AI’s CDK —
seike460
PRO
1
240
1B+ /day規模のログを管理する技術
broadleaf
0
140
The Past, Present, and Future of Enterprise Java
ivargrimstad
0
210
ローカルLLMでどこまでコードが書けるか -拡張版 / How much code can be written on a local LLM Extended
kishida
12
4.8k
トークンをケチるな、設計しろ:GitHub Copilotを賢く使うコンテキスト戦略
ochtum
0
320
分散システム、なんですぐ死んでしまうん?耐障害性を高めたいあなたのためのレジリエンスパターン入門
mshibuya
7
6k
【やさしく解説 設計編・中級 #4】ルールの寿命と、システムの年輪
panda728
PRO
2
130
20260623_Loop Engineeringで自分の分身の問い合わせBotを作る
ryugen04
0
210
Featured
See All Featured
実際に使うSQLの書き方 徹底解説 / pgcon21j-tutorial
soudai
PRO
201
75k
Fight the Zombie Pattern Library - RWD Summit 2016
marcelosomers
234
17k
[RailsConf 2023 Opening Keynote] The Magic of Rails
eileencodes
31
10k
Ecommerce SEO: The Keys for Success Now & Beyond - #SERPConf2024
aleyda
1
2.1k
The innovator’s Mindset - Leading Through an Era of Exponential Change - McGill University 2025
jdejongh
PRO
1
220
Jamie Indigo - Trashchat’s Guide to Black Boxes: Technical SEO Tactics for LLMs
techseoconnect
PRO
0
340
Design in an AI World
tapps
1
260
Why You Should Never Use an ORM
jnunemaker
PRO
61
9.9k
The Art of Programming - Codeland 2020
erikaheidi
57
14k
Design of three-dimensional binary manipulators for pick-and-place task avoiding obstacles (IECON2024)
konakalab
0
490
Building Experiences: Design Systems, User Experience, and Full Site Editing
marktimemedia
0
550
Six Lessons from altMBA
skipperchong
29
4.3k
Transcript
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}")