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
340
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
330
Comparison of Packaging Tools in 2023 (PyCon TW 2023)
peacock0803sz
1
88
Getting Started with Statically Typed Programming in Python 3.10 / PyConUS2022
peacock0803sz
0
98
Getting Started with Statically Typed Programming in Python 3.10 / PyCon APAC 2021
peacock0803sz
0
200
Python3.10からはじめる型ヒント / stapy74
peacock0803sz
0
2.1k
Announcement from PyCon JP 2021
peacock0803sz
0
220
Getting Started with Statically Typed Programming in Python 3.10
peacock0803sz
0
1.6k
2021年の型駆動開発 / type-driven-design-in-2021-python
peacock0803sz
2
410
Other Decks in Technology
See All in Technology
2人で作ったAIダッシュボードが、開発組織の次の一手を照らした話― Cursor × SpecKit × 可視化の実践 ― Qiita AI Summit
noalisaai
1
320
Kubecon NA 2025: DRA 関連の Recap と社内 GPU 基盤での課題
kevin_namba
0
110
全員が「作り手」になる。職能の壁を溶かすプロトタイプ開発。
hokuo
1
660
Amazon Bedrock AgentCore 認証・認可入門
hironobuiga
2
470
SREが向き合う大規模リアーキテクチャ 〜信頼性とアジリティの両立〜
zepprix
0
300
AWS Devops Agent ~ 自動調査とSlack統合をやってみた! ~
kubomasataka
3
300
15 years with Rails and DDD (AI Edition)
andrzejkrzywda
0
130
セキュリティについて学ぶ会 / 2026 01 25 Takamatsu WordPress Meetup
rocketmartue
1
210
【インシデント入門】サイバー攻撃を受けた現場って何してるの?
shumei_ito
0
1.3k
Deno・Bunの標準機能やElysiaJSを使ったWebSocketサーバー実装 / ラーメン屋を貸し切ってLT会! IoTLT 2026新年会
you
PRO
0
210
AIとともに歩む情報セキュリティ / Information Security with AI
kanny
4
3k
みんなだいすきALB、NLBの 仕組みから最新機能まで総おさらい / Mastering ALB & NLB: Internal Mechanics and Latest Innovations
kaminashi
0
170
Featured
See All Featured
The Mindset for Success: Future Career Progression
greggifford
PRO
0
230
Google's AI Overviews - The New Search
badams
0
900
コードの90%をAIが書く世界で何が待っているのか / What awaits us in a world where 90% of the code is written by AI
rkaga
59
42k
Claude Code どこまでも/ Claude Code Everywhere
nwiizo
61
52k
DevOps and Value Stream Thinking: Enabling flow, efficiency and business value
helenjbeal
1
88
Lightning Talk: Beautiful Slides for Beginners
inesmontani
PRO
1
430
JAMstack: Web Apps at Ludicrous Speed - All Things Open 2022
reverentgeek
1
320
Save Time (by Creating Custom Rails Generators)
garrettdimon
PRO
32
2k
Designing for humans not robots
tammielis
254
26k
The Invisible Side of Design
smashingmag
302
51k
BBQ
matthewcrist
89
10k
Digital Projects Gone Horribly Wrong (And the UX Pros Who Still Save the Day) - Dean Schuster
uxyall
0
240
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