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ではじめる今風な型プログラミング / osc21do
Search
Sponsored
·
SiteGround - Reliable hosting with speed, security, and support you can count on.
→
Peacock
June 26, 2021
Technology
370
1
Share
Embed
Copy iframe code
Copy JS code
Copy link
Start on current slide
Pythonではじめる今風な型プログラミング / osc21do
Open Source Conference 2021 Hokkaidoでの発表資料
Peacock
June 26, 2021
More Decks by Peacock
See All by Peacock
Comparison of Packaging Tools in 2023 (PyCon APAC 2023)
peacock0803sz
0
390
Comparison of Packaging Tools in 2023 (PyCon TW 2023)
peacock0803sz
1
140
Getting Started with Statically Typed Programming in Python 3.10 / PyConUS2022
peacock0803sz
0
160
Getting Started with Statically Typed Programming in Python 3.10 / PyCon APAC 2021
peacock0803sz
0
230
Python3.10からはじめる型ヒント / stapy74
peacock0803sz
0
2.3k
Announcement from PyCon JP 2021
peacock0803sz
0
240
Getting Started with Statically Typed Programming in Python 3.10
peacock0803sz
0
1.7k
2021年の型駆動開発 / type-driven-design-in-2021-python
peacock0803sz
2
460
Other Decks in Technology
See All in Technology
局所最適は悪ではない。壊れているのは指標です。量と質を同時に見る先行指標の設計
recruitengineers
PRO
2
230
『SAR衛星データ解析入門』のご紹介とその応用
syuchimu
0
140
ソフトウェア ファクトリー - 再現性のあるソフトウェアの工場づくり / Software factory
iktakahiro
7
5.2k
10年後、Engineering 行為を剥奪されるとして、わたしたちは、どう、何を創ればいいだろうか。 / If Engineering Is Taken Away in 10 Years, How and What Should We Create?
bitkey
PRO
1
220
ポケモン対戦を自動で記録して振り返ろう
fufufukakaka
0
170
CSS2026:OWS研究会・招待講演「世界観を、実装する」
atsush1_sada
2
130
Codex を使った障害対応机上演習の実際
orgachem
PRO
0
230
野良MCPサーバーを排除せよ!MCPサーバーのガバナンス
yukiogawa
1
140
AI駆動開発における開発環境のセキュリティの考え方
yamahiro
0
200
AIをリアル世界に解き放つ 〜M5Stack×AIであなたのアイディアを手の平に〜
hamadakoji
1
210
コンテナ運用におけるネットワーク・コンテナコストの削減方法/How to Reduce Network and Container Costs in Container Operations
masakiokuda
2
370
DevelopersIO 2026 Tokyo 現時点の衛星通信サービスの現状を整理してみる
maroon1st
0
110
Featured
See All Featured
Deep Space Network (abreviated)
tonyrice
0
380
From π to Pie charts
rasagy
1
400
SEO in 2025: How to Prepare for the Future of Search
ipullrank
3
3.9k
The SEO identity crisis: Don't let AI make you average
varn
0
590
Leveraging LLMs for student feedback in introductory data science courses - posit::conf(2025)
minecr
1
440
Information Architects: The Missing Link in Design Systems
soysaucechin
1
1.2k
Dominate Local Search Results - an insider guide to GBP, reviews, and Local SEO
greggifford
PRO
0
370
<Decoding/> the Language of Devs - We Love SEO 2024
nikkihalliwell
1
360
ラッコキーワード サービス紹介資料
rakko
3
5.4M
How to Build an AI Search Optimization Roadmap - Criteria and Steps to Take #SEOIRL
aleyda
1
2.2k
Making Projects Easy
brettharned
120
6.8k
Kristin Tynski - Automating Marketing Tasks With AI
techseoconnect
PRO
0
550
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