Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Speaker Deck
PRO
Sign in
Sign up for free
Python Type Hints
Sunghyun Hwang
March 25, 2017
Programming
6
1.8k
Python Type Hints
제 3회 파이썬 격월 세미나에서 발표한 [Python Type Hints] 발표 슬라이드입니다. (
https://www.facebook.com/groups/pythonkorea/
)
Sunghyun Hwang
March 25, 2017
Tweet
Share
More Decks by Sunghyun Hwang
See All by Sunghyun Hwang
MongoDB in Banksalad
sunghyunzz
0
250
[ConSalad 05] from banksalad import python
sunghyunzz
0
130
from banksalad import python
sunghyunzz
0
550
사실주의 베이컨
sunghyunzz
1
64
Clean Architecture (in Android) Revised
sunghyunzz
1
880
학습하는 조직과 Python: 뱅크샐러드 사례를 중심으로
sunghyunzz
2
1.6k
The Secrets of Cooperation
sunghyunzz
0
400
Pragmatic Python
sunghyunzz
1
92
Practical FP in Kotlin
sunghyunzz
4
1.2k
Other Decks in Programming
See All in Programming
SHOWROOMの分析目的を意識した伝え方・コミュニケーション
hatapu
0
230
Zynq MP SoC で楽しむエッジコンピューティング ~RTLプログラミングのススメ~
ryuz88
0
320
Most Valuable Bug(?) ~インシデント未遂から得た学び~
tatsumiakahori
0
140
CDKでValidationする本当の方法 / cdk-validation
gotok365
1
190
Functional Data Engineering - A Blueprint for adopting functional principles in data pipeline
vananth22
0
170
Azure Functionsをサクッと開発、サクッとデプロイ/vscodeconf2023-baba
nina01
1
330
ちょうぜつ改め21世紀ふつうのソフトウェア設計
tanakahisateru
7
6.3k
OIDC仕様に準拠した Makuake ID連携基盤構築の裏側
ymtdzzz
0
410
10年以上続くプロダクトの フロントエンド刷新プロジェクトのふりかえり
yotahada3
2
320
T3 Stack and TypeScript ecosystem
quramy
3
720
Ruby Pattern Matching
bkuhlmann
0
610
tidy_rpart
bk_18
0
580
Featured
See All Featured
Raft: Consensus for Rubyists
vanstee
130
5.7k
Pencils Down: Stop Designing & Start Developing
hursman
114
10k
Stop Working from a Prison Cell
hatefulcrawdad
263
18k
A Tale of Four Properties
chriscoyier
149
21k
From Idea to $5000 a Month in 5 Months
shpigford
374
44k
A designer walks into a library…
pauljervisheath
199
16k
Templates, Plugins, & Blocks: Oh My! Creating the theme that thinks of everything
marktimemedia
15
1.2k
How New CSS Is Changing Everything About Graphic Design on the Web
jensimmons
214
12k
The Brand Is Dead. Long Live the Brand.
mthomps
48
2.9k
XXLCSS - How to scale CSS and keep your sanity
sugarenia
236
1.1M
Become a Pro
speakerdeck
PRO
6
3.2k
Fight the Zombie Pattern Library - RWD Summit 2016
marcelosomers
227
16k
Transcript
Python Type Hints presenter: str = "sunghyunzz"
PEP 484 - Type Hints • PEP 3107 - Function
Annotations
PEP 484 - Type Hints • PEP 3107 - Function
Annotations • 2014-09-29
PEP 484 - Type Hints • PEP 3107 - Function
Annotations • 2014-09-29 • Python 3.5
def add(a: int, b: int) -> int: return a +
b
def print_sum(a: int, b: int) -> None: print(a + b)
def get_list(a: int, b: int) -> list: return [a, b]
def get_list(a: int, b: int) -> list: return [a, b]
from typing import List def get_list(a: int, b: int) -> List[int]: return [a, b]
def get_list(a: int, b: int) -> List: return ['a', a,
'b', b, 'a + b', a + b]
def get_list(a: int, b: int) -> List: return ['a', a,
'b', b, 'a + b', a + b]
def get_list(a: int, b: int) -> list: return [a, b]
from typing import Any, List def get_list(a: int, b: int) -> List[Any]: return ['a', a, 'b', b, 'a + b', a + b]
def func(text: str) -> str: result: int = some_complex_func(text) return
str(result)
class Person: def __init__(self, name: str) -> None: self.name: str
= name self.length_of_name: int = len(name)
from typing import List, Union result: List[Union[int, str]] = [1,
'a', 2, 'b']
from typing import Optional, Union assert Optional[int] == Union[int, None]
from typing import Dict, Set def get_dict(a: int) -> Dict[int,
str]: return { a: str(a), a + 1: str(a + 1) } def get_set(a: int) -> Set[int]: return {a, a + 1}
from typing import Tuple def get_tuple(a: int, b: int) ->
Tuple[int]: return a, b # Expected type 'Tuple[int]', got 'Tuple[int, int]' instead
from typing import Tuple def get_tuple(a: int, b: int) ->
Tuple[int, int]: return a, b
from typing import Tuple def get_tuple() -> Tuple[int, int, int,
int, int, int, int, int, int, int]: return 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
from typing import Tuple def get_tuple() -> Tuple[int, ...]: return
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
from typing import Callable def add_lazy(a: int, b: int): def
f() -> int: return a + b return f
from typing import Callable def add_lazy(a: int, b: int) ->
Callable[[], int]: def f() -> int: return a + b return f
from typing import Callable def run(f: Callable[[int, str], int], a:
int, b: str) -> int: return f(a, b)
def run(f: Callable[..., int], *args) -> int: return f(args)
def run(f: Callable[..., int], *args: int) -> int: return f(args)
def run( f: Callable[[Dict[str, int]], int], **kwargs: int ) ->
int: return f(kwargs)
def run( f: Callable[[Dict[str, int]], int], **kwargs: int ) ->
int: return f(kwargs)
def run( f: Callable[[Dict[str, int]], int], **kwargs: int ) ->
int: return f(kwargs)
IntReturningFunction = Callable[..., int] def run(f: IntReturningFunction) -> int: return
f(1, 2, 3, 4, 5)
def fetch(_id: int, category: int) -> Transaction: pass
EntityID = int def fetch(_id: EntityID, category: int) -> Transaction:
pass
class Person: def get_children(self) -> List[Person]: pass
class Person: def get_children(self) -> List[Person]: pass NameError: name 'Person'
is not defined
class Person: def get_children(self) -> List[Person]: pass def get_children(self) ->
List['Person']: pass
from abc import ABCMeta, abstractmethod from typing import Generic, TypeVar
T = TypeVar('T') class Person: pass class Mapper(Generic[T], metaclass=ABCMeta): @classmethod @abstractmethod def from_dict(cls, request: dict) -> T: pass def convert(mapper: Mapper[Person], data: dict) -> Person: return mapper.from_dict(data)
from abc import ABCMeta, abstractmethod from typing import Generic, TypeVar
T = TypeVar('T') class Person: pass class Mapper(Generic[T], metaclass=ABCMeta): @classmethod @abstractmethod def from_dict(cls, request: dict) -> T: pass def convert(mapper: Mapper[Person], data: dict) -> Person: return mapper.from_dict(data)
from abc import ABCMeta, abstractmethod from typing import Generic, TypeVar
T = TypeVar('T') class Person: pass class Mapper(Generic[T], metaclass=ABCMeta): @classmethod @abstractmethod def from_dict(cls, request: dict) -> T: pass def convert(mapper: Mapper[Person], data: dict) -> Person: return mapper.from_dict(data)
from abc import ABCMeta, abstractmethod from typing import Generic, TypeVar
T = TypeVar('T') class Person: pass class Mapper(Generic[T], metaclass=ABCMeta): @classmethod @abstractmethod def from_dict(cls, request: dict) -> T: pass def convert(mapper: Mapper[Person], data: dict) -> Person: return mapper.from_dict(data)
from abc import ABCMeta, abstractmethod from typing import Generic, TypeVar
T = TypeVar('T') class Person: pass class Mapper(Generic[T], metaclass=ABCMeta): @classmethod @abstractmethod def from_dict(cls, request: dict) -> T: pass def convert(mapper: Mapper[Person], data: dict) -> Person: return mapper.from_dict(data)
from abc import ABCMeta, abstractmethod from typing import Generic, TypeVar
T = TypeVar('T') class Person: pass class Mapper(Generic[T], metaclass=ABCMeta): @classmethod @abstractmethod def from_dict(cls, request: dict) -> T: pass def convert(mapper: Mapper[Person], data: dict) -> Person: return mapper.from_dict(data)
python2 support from typing import List def hello(): # type:
() -> None print 'hello' class Example: def method(self, lst, opt=0, *args, **kwargs): # type: (List[str], int, *str, **bool) -> int """Docstring comes after type comment."""
# some other package (math.py) def add(a, b): return a
+ b
# stub (math.pyi) def add(a: float, b: float) -> float:
…
None
python/typeshed • contains external type annotations for the Python standard
library and Python builtins
python/typeshed • contains external type annotations for the Python standard
library and Python builtins • as well as third party packages.
None
None
None
None
None
None
[mypy] disallow_untyped_defs = True strict_optional = True warn_redundant_casts = True
:+1: • ޙࢲച ӝמ (ӝઓ docstring convention )
:+1: • ޙࢲച ӝמ (ӝઓ docstring convention ) • IDE/ী٣ఠ
ఋੑ ୶ۿ ѐࢶ
:+1: • ޙࢲച ӝמ (ӝઓ docstring convention ) • IDE/ী٣ఠ
ఋੑ ୶ۿ ѐࢶ • Type Checkerܳ ాೠ पࣻ ߑ
:-1: • ҃ী ٮۄ ࠛਃೠ ٘ ୶о
:-1: • ҃ী ٮۄ ࠛਃೠ ٘ ୶о • (ই) ࣗ
ࠗೠ ఋੑ दझమ
“Python is dynamically typed and we like it that way!”
- Guido van Rossum
ۨפझীࢲח • ఋੑ ݺदо ٘ оةࢿਸ ֫ੋҊ ਵݴ ۽ં ҙܻ
࠺ਊਸ ծ ࣻ Ҋ ౸ױೞৈ بੑ೮णפ.
ۨפझীࢲח • ఋੑ ݺदо ٘ оةࢿਸ ֫ੋҊ ਵݴ ۽ં ҙܻ
࠺ਊਸ ծ ࣻ Ҋ ౸ױೞৈ بੑ೮णפ. • नӏ ۽ંח CI җীࢲ mypyܳ प೯פ.
ۨפझীࢲח • ఋੑ ݺदо ٘ оةࢿਸ ֫ੋҊ ਵݴ ۽ં ҙܻ
࠺ਊਸ ծ ࣻ Ҋ ౸ױೞৈ بੑ೮णפ. • नӏ ۽ંח CI җীࢲ mypyܳ प೯פ. • ఋੑ दझమ ೠ҅۽ ੋ೧ ࠛਃೠ ٘ܳ ࢿ೧ঠ ೡ ٸ ীח @typing.no_type_check
ߛ࢟۞٘ܳ ݅٘ח ۨפझীࢲ ൞ ৬ ೣԋೡ ࢲߡ ূפয ٜ࠙ਸ Ҋ
णפ. Python, aiohttp, django
Questions github: sunghyunzz email:
[email protected]