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
Sponsored
·
SiteGround - Reliable hosting with speed, security, and support you can count on.
→
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
SODA - FACT BOOK(EN)
sodainc
1
250
[Kotlin Fest 2026] eBPF Tracing for Kotlin
takehaya
1
270
Augmenting AI with the Power of Jakarta EE
ivargrimstad
0
340
Zero-Tap Sign-In対応、結局何をすればいいの?
mitohato14
0
2.2k
graphql-ruby を Spinel で速くしようとした話
mtsmfm
0
150
AIが実装を担う時代の「技術設計」と「チームマネジメント」
kamina_zzz
2
270
AI-Powered Domain-Driven Design
ziobrando
0
460
Будущее локальных LLM – Алексей Голобурдин, PythoNN
sobolevn
0
120
Goコンパイラを作ってGoをもっと理解する / Build a Go compiler to better understand Go
ikura_hamu
0
130
Claude Code ハーネスDeep Dive – 君はどこまで制御する? -
takateeen_knj
6
5.9k
우리의 Nitro Modules는 당신의 Turbo Modules보다 아름답다
l2hyunwoo
0
260
느린 네트워크와 저사양 디바이스 사용자를 위한 웹뷰 로딩 시간 개선기
kmkim
1
240
Featured
See All Featured
Leveraging Curiosity to Care for An Aging Population
cassininazir
1
570
Testing 201, or: Great Expectations
jmmastey
46
8.4k
The Spectacular Lies of Maps
axbom
PRO
1
1.1k
The Illustrated Children's Guide to Kubernetes
chrisshort
51
53k
Connecting the Dots Between Site Speed, User Experience & Your Business [WebExpo 2025]
tammyeverts
11
1.1k
WCS-LA-2024
lcolladotor
0
1k
Distributed Sagas: A Protocol for Coordinating Microservices
caitiem20
333
23k
Technical Leadership for Architectural Decision Making
baasie
4
650
Tell your own story through comics
letsgokoyo
1
1.1k
Claude Code どこまでも/ Claude Code Everywhere
nwiizo
68
60k
Groundhog Day: Seeking Process in Gaming for Health
codingconduct
0
480
How to Build an AI Search Optimization Roadmap - Criteria and Steps to Take #SEOIRL
aleyda
1
2.3k