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ではじめる今風な型プログラミング / osc21do
Search
Peacock
June 26, 2021
Technology
1
310
Pythonではじめる今風な型プログラミング / osc21do
Open Source Conference 2021 Hokkaidoでの発表資料
Peacock
June 26, 2021
Tweet
Share
More Decks by Peacock
See All by Peacock
Comparison of Packaging Tools in 2023 (PyCon APAC 2023)
peacock0803sz
0
300
Comparison of Packaging Tools in 2023 (PyCon TW 2023)
peacock0803sz
0
75
Getting Started with Statically Typed Programming in Python 3.10 / PyConUS2022
peacock0803sz
0
83
Getting Started with Statically Typed Programming in Python 3.10 / PyCon APAC 2021
peacock0803sz
0
160
Python3.10からはじめる型ヒント / stapy74
peacock0803sz
0
1.5k
Announcement from PyCon JP 2021
peacock0803sz
0
200
Getting Started with Statically Typed Programming in Python 3.10
peacock0803sz
0
1.5k
2021年の型駆動開発 / type-driven-design-in-2021-python
peacock0803sz
2
350
Other Decks in Technology
See All in Technology
Agentic DevOps時代の生存戦略
kkamegawa
1
1.3k
プロダクトエンジニアリング組織への歩み、その現在地 / Our journey to becoming a product engineering organization
hiro_torii
0
120
Agentic Workflowという選択肢を考える
tkikuchi1002
1
480
Welcome to the LLM Club
koic
0
160
ハノーバーメッセ2025座談会.pdf
iotcomjpadmin
0
160
5min GuardDuty Extended Threat Detection EKS
takakuni
0
120
Liquid Glass革新とSwiftUI/UIKit進化
fumiyasac0921
0
180
【TiDB GAME DAY 2025】Shadowverse: Worlds Beyond にみる TiDB 活用術
cygames
0
1k
ひとり情シスなCTOがLLMと始めるオペレーション最適化 / CTO's LLM-Powered Ops
yamitzky
0
420
Oracle Audit Vault and Database Firewall 20 概要
oracle4engineer
PRO
3
1.7k
Node-RED × MCP 勉強会 vol.1
1ftseabass
PRO
0
140
AIのAIによるAIのための出力評価と改善
chocoyama
2
540
Featured
See All Featured
Fireside Chat
paigeccino
37
3.5k
Fashionably flexible responsive web design (full day workshop)
malarkey
407
66k
Making Projects Easy
brettharned
116
6.3k
Building Applications with DynamoDB
mza
95
6.5k
Code Reviewing Like a Champion
maltzj
524
40k
Optimizing for Happiness
mojombo
379
70k
Cheating the UX When There Is Nothing More to Optimize - PixelPioneers
stephaniewalter
281
13k
Practical Orchestrator
shlominoach
188
11k
Sharpening the Axe: The Primacy of Toolmaking
bcantrill
44
2.4k
Visualization
eitanlees
146
16k
Let's Do A Bunch of Simple Stuff to Make Websites Faster
chriscoyier
507
140k
The MySQL Ecosystem @ GitHub 2015
samlambert
251
13k
Transcript
Python ではじめる今風な 型プログラミング 6/25(Sat), OSC2021 Online/Hokkaido
1. そもそも: 型ヒントとは 2. 型ヒント入門編: 小さく始める i. 関数の戻り値・引数 ii. 標準で使える組み込み型
3. 少し発展編: typing モジュール i. Genarator, Callable, TypeVar, Genarics, etc... 4. 最近のアップデート・新機能を以前のバージョンでも使うには 今日話すこと 2 / 24
名前: Peacock / 高井 陽一 Twitter / GitHub / Facebook:
peacock0803sz CMS コミュニケーションズでWeb なPython を書いている PyCon JP Association 関係の活動 PyCon JP 2020, 2021 スタッフ PyCon JP TV ディレクター 自己紹介 3 / 24
OSC は2019 Tokyo/Fall から 2020 はちょこちょこスタッフやってたりしてました パブリックな場所で話すのが初めてなのでどうかお手柔らかに Zoom 発表さみしいのでリアクションたくさんもらえると嬉しい です
Twitter 実況も歓迎( あとで見に行きます 資料はSpeakerDeck にアップロード済みです 自己紹介(続き) 4 / 24
Motivation とこの発表のゴール 5 / 24
Let's begin!
3.5 まで完全な動的型付け言語だったPython に、型を導入しようとい う話 あくまで「ヒント」でありコメント 実行時に評価はされず、TypeScipt のようにコンパイルエラーも 出ない def greet(name:
str) -> str: return "Hello, " + name そもそも: 型ヒントとは 7 / 24
型ヒント入門編: 小さく始める 最初から頑張って書くのはつらいので小さく始める
全部に書こうとしなくていい Java やC みたいに全部書く必要はない 基本的に型をつけるときは名前の後ろに : を書いて型 関数の戻り値は -> を使う
def greet(name: str) -> str: return "Hello, " + name まずは関数の引数・戻り値から 9 / 24
エディタで参照したときに型がわかる 間違ったものを渡そうとしたときに怒ってくれる 何が嬉しいのか? 10 / 24
bool , bytes , float , int , str :
何もしなくても使える None : 何も返さない関数に使う dict , frozenset , list , set , tuple Collections は中の型を [] で書ける 3.9 以降のみ 3.7, 3.8 は from __future__ import annotaions ( 後述) を書 く 3.6 は typing ( 次項) から大文字始まりのものをimport する ex: list[str] , dict[str, int] refs: python.jp での紹介記事、公式ドキュメント( 英語) 何もimport しなくていい組み込み型 11 / 24
Generics 系は3.9 までは from typing import ... を書いていた コレクション、プロトコル関係など 3.9
からは後述する書き方になって、非推奨に (3.9 から非推奨) typing モジュールからimport する 12 / 24
あらゆる型のインスタンスを保持できる 使わないに越したことはない 必要なときには typing からimport して使う from typing import Any
unknown_variable: Any Any 13 / 24
少し発展編: Generics 型
Union : 合併型。3.10 以降は | で表せる 例: 文字列と整数をどっちも受け入れる関数 from __future__
import annoations # 3.7 - 3.9は必要 def normalize_year(year: int | str) -> int: if isinstance(year, int): return year # ここではyearは数値 # これ以降ではyearは文字列 if year.startswith("昭和"): return int(year[2:]) + 1925 elif year.startswith("平成"): return int(year[2:]) + 1988 elif year.startswith("令和"): return int(year[2:]) + 2018 else: raise ValueError('unsupported style') from typing import Union # for 3.6 def normalize_year(year: Union[int, str]) -> int: pass 合併型(Union) 15 / 24
nullable, None とのUnion と等価 Union と同じように振る舞ってくれる 関数の戻り値とかに使うと伝播してしまうので、使い方は要注意 from typing import
Optional age: Optional[int] age = 17 age = None # これも有効 age: int | None # 3.9以降ならこれでもいい Optional 型 16 / 24
デコレーター関数など、関数を引数に取る関数を書くときに使える from collections.abc import Callable # 3.9以降 from fuctools import
wraps from typing import Callable # 3.8以前 def validate(func: Callable) -> Callable[..., Callable | tuple[Response, Literal[400]]]: @wraps(func) def wrapper(*args, **kw) -> Callable | tuple[Response, Literal[400]]: try: j = request.json if j is None: raise BadRequest except BadRequest: return jsonify({"data": [], "errors": {"message": ERROR_MESSAGE, "code": 400}}), 400 return func(*args, **kw) return wrapper Callable( 呼び出し可能オブジェクト) 17 / 24
最近のアップデート・新機能を以前の バージョンでも使うには
https:/ /www.python.org/downloads/ バージョン ステータス 初回リリース EOS PEP 3.9 バグ修正 2020-10-05
2025-10 596 3.8 バグ修正 2019-10-14 2024-10 569 3.7 セキュリティ 2018-06-27 2023-06-27 537 3.6 セキュリティ 2016-12-23 2021-12-23 494 最近のアップデート事情 19 / 24
後方互換性のために存在している 破壊的変更がいつ導入されて、必須になったかが書かれている typing の他にも3.x の機能を2.x でも呼び出すときなどに使っていた ex) print_func , unicode_literals
etc ... refs: 公式ドキュメント__future__, future statement __future__ モジュール: (dunder future) とは 20 / 24
3.9, 3.10 で使えるようになった ( る)typing 関連の新機能たち
Generics 型定義( [] を使って中の型を書ける) のimport 元が変わった 3.8 までは typing からだったけど、分散した
list , tuple , dict などの __builtins__ なら何もせずに小文字始 まりにする collections 系(deque, defaultdict) などは collections から iterable, callable などプロトコル関係は collections.abc から 正規表現は re コンテキスト関連は contextlib 3.9 から: 標準Collections 型のGenerics 22 / 24
前述した合併型(Union) が演算子として使える isinstance() で聞くときにも使える TypeScipt などがこの記法なのでより直感的 3.10 の他のtyping 関連の新機能は複雑なのでは紹介しない 引数仕様変数、明示的型エイリアス、ユーザー定義型ガード
See also: What's New In Python 3.10 3.10 から: Union 型演算子 23 / 24
小さいところから、こつこつと 関数の返値、戻り値からやるのがおすすめ ここ1,2 年で注目が高まってきて、アップデートも速い分野 書いていて気持ちいい、素敵なPython ライフ? を! まとめ 24 /
24