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
Sponsored
·
Your Podcast. Everywhere. Effortlessly.
Share. Educate. Inspire. Entertain. You do you. We'll handle the rest.
→
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
89
Getting Started with Statically Typed Programming in Python 3.10 / PyConUS2022
peacock0803sz
0
99
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
FinTech SREのAWSサービス活用/Leveraging AWS Services in FinTech SRE
maaaato
0
130
名刺メーカーDevグループ 紹介資料
sansan33
PRO
0
1k
レガシー共有バッチ基盤への挑戦 - SREドリブンなリアーキテクチャリングの取り組み
tatsukoni
0
210
MCPでつなぐElasticsearchとLLM - 深夜の障害対応を楽にしたい / Bridging Elasticsearch and LLMs with MCP
sashimimochi
0
150
Kiro IDEのドキュメントを全部読んだので地味だけどちょっと嬉しい機能を紹介する
khmoryz
0
170
プロポーザルに込める段取り八分
shoheimitani
1
180
Amazon Bedrock Knowledge Basesチャンキング解説!
aoinoguchi
0
120
Frontier Agents (Kiro autonomous agent / AWS Security Agent / AWS DevOps Agent) の紹介
msysh
3
150
M&A 後の統合をどう進めるか ─ ナレッジワーク × Poetics が実践した組織とシステムの融合
kworkdev
PRO
1
420
インフラエンジニア必見!Kubernetesを用いたクラウドネイティブ設計ポイント大全
daitak
0
330
Tebiki Engineering Team Deck
tebiki
0
24k
Embedded SREの終わりを設計する 「なんとなく」から計画的な自立支援へ
sansantech
PRO
3
2.2k
Featured
See All Featured
Neural Spatial Audio Processing for Sound Field Analysis and Control
skoyamalab
0
160
Agile that works and the tools we love
rasmusluckow
331
21k
StorybookのUI Testing Handbookを読んだ
zakiyama
31
6.6k
Digital Projects Gone Horribly Wrong (And the UX Pros Who Still Save the Day) - Dean Schuster
uxyall
0
320
The Art of Delivering Value - GDevCon NA Keynote
reverentgeek
16
1.8k
Producing Creativity
orderedlist
PRO
348
40k
Building Applications with DynamoDB
mza
96
6.9k
GraphQLとの向き合い方2022年版
quramy
50
14k
The AI Search Optimization Roadmap by Aleyda Solis
aleyda
1
5.2k
Getting science done with accelerated Python computing platforms
jacobtomlinson
2
110
Building Experiences: Design Systems, User Experience, and Full Site Editing
marktimemedia
0
410
KATA
mclloyd
PRO
34
15k
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