Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Python Type Hints

Python Type Hints

제 3회 파이썬 격월 세미나에서 발표한 [Python Type Hints] 발표 슬라이드입니다. (https://www.facebook.com/groups/pythonkorea/)

Sunghyun Hwang

March 25, 2017
Tweet

More Decks by Sunghyun Hwang

Other Decks in Programming

Transcript

  1. Python Type Hints
    presenter: str = "sunghyunzz"

    View full-size slide

  2. PEP 484 - Type Hints
    • PEP 3107 - Function Annotations

    View full-size slide

  3. PEP 484 - Type Hints
    • PEP 3107 - Function Annotations
    • 2014-09-29

    View full-size slide

  4. PEP 484 - Type Hints
    • PEP 3107 - Function Annotations
    • 2014-09-29
    • Python 3.5

    View full-size slide

  5. def add(a: int, b: int) -> int:
    return a + b

    View full-size slide

  6. def print_sum(a: int, b: int) -> None:
    print(a + b)

    View full-size slide

  7. def get_list(a: int, b: int) -> list:
    return [a, b]

    View full-size slide

  8. 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]

    View full-size slide

  9. def get_list(a: int, b: int) -> List:
    return ['a', a, 'b', b, 'a + b', a + b]

    View full-size slide

  10. def get_list(a: int, b: int) -> List:
    return ['a', a, 'b', b, 'a + b', a + b]

    View full-size slide

  11. 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]

    View full-size slide

  12. def func(text: str) -> str:
    result: int = some_complex_func(text)
    return str(result)

    View full-size slide

  13. class Person:
    def __init__(self, name: str) -> None:
    self.name: str = name
    self.length_of_name: int = len(name)

    View full-size slide

  14. from typing import List, Union
    result: List[Union[int, str]] = [1, 'a', 2, 'b']

    View full-size slide

  15. from typing import Optional, Union
    assert Optional[int] == Union[int, None]

    View full-size slide

  16. 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}

    View full-size slide

  17. 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

    View full-size slide

  18. from typing import Tuple
    def get_tuple(a: int, b: int) -> Tuple[int, int]:
    return a, b

    View full-size slide

  19. 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

    View full-size slide

  20. from typing import Tuple
    def get_tuple() -> Tuple[int, ...]:
    return 1, 2, 3, 4, 5, 6, 7, 8, 9, 10

    View full-size slide

  21. from typing import Callable
    def add_lazy(a: int, b: int):
    def f() -> int:
    return a + b
    return f

    View full-size slide

  22. from typing import Callable
    def add_lazy(a: int, b: int) -> Callable[[], int]:
    def f() -> int:
    return a + b
    return f

    View full-size slide

  23. from typing import Callable
    def run(f: Callable[[int, str], int], a: int, b: str) -> int:
    return f(a, b)

    View full-size slide

  24. def run(f: Callable[..., int], *args) -> int:
    return f(args)

    View full-size slide

  25. def run(f: Callable[..., int], *args: int) -> int:
    return f(args)

    View full-size slide

  26. def run(
    f: Callable[[Dict[str, int]], int],
    **kwargs: int
    ) -> int:
    return f(kwargs)

    View full-size slide

  27. def run(
    f: Callable[[Dict[str, int]], int],
    **kwargs: int
    ) -> int:
    return f(kwargs)

    View full-size slide

  28. def run(
    f: Callable[[Dict[str, int]], int],
    **kwargs: int
    ) -> int:
    return f(kwargs)

    View full-size slide

  29. IntReturningFunction = Callable[..., int]
    def run(f: IntReturningFunction) -> int:
    return f(1, 2, 3, 4, 5)

    View full-size slide

  30. def fetch(_id: int, category: int) -> Transaction:
    pass

    View full-size slide

  31. EntityID = int
    def fetch(_id: EntityID, category: int) -> Transaction:
    pass

    View full-size slide

  32. class Person:
    def get_children(self) -> List[Person]:
    pass

    View full-size slide

  33. class Person:
    def get_children(self) -> List[Person]:
    pass
    NameError: name 'Person' is not defined

    View full-size slide

  34. class Person:
    def get_children(self) -> List[Person]:
    pass
    def get_children(self) -> List['Person']:
    pass

    View full-size slide

  35. 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)

    View full-size slide

  36. 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)

    View full-size slide

  37. 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)

    View full-size slide

  38. 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)

    View full-size slide

  39. 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)

    View full-size slide

  40. 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)

    View full-size slide

  41. 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."""

    View full-size slide

  42. # some other package (math.py)
    def add(a, b):
    return a + b

    View full-size slide

  43. # stub (math.pyi)
    def add(a: float, b: float) -> float: …

    View full-size slide

  44. python/typeshed
    • contains external type annotations for the
    Python standard library and Python builtins

    View full-size slide

  45. python/typeshed
    • contains external type annotations for the
    Python standard library and Python builtins
    • as well as third party packages.

    View full-size slide

  46. [mypy]
    disallow_untyped_defs = True
    strict_optional = True
    warn_redundant_casts = True

    View full-size slide

  47. :+1:
    • ޙࢲച੄ ӝמ (ӝઓ੄ docstring convention ؀୓)

    View full-size slide

  48. :+1:
    • ޙࢲച੄ ӝמ (ӝઓ੄ docstring convention ؀୓)
    • IDE/ী٣ఠ ఋੑ ୶ۿ ѐࢶ

    View full-size slide

  49. :+1:
    • ޙࢲച੄ ӝמ (ӝઓ੄ docstring convention ؀୓)
    • IDE/ী٣ఠ ఋੑ ୶ۿ ѐࢶ
    • ੿੸ Type Checkerܳ ాೠ पࣻ ߑ૑

    View full-size slide

  50. :-1:
    • ҃਋ী ٮۄ ࠛ೙ਃೠ ௏٘੄ ୶о

    View full-size slide

  51. :-1:
    • ҃਋ী ٮۄ ࠛ೙ਃೠ ௏٘੄ ୶о
    • (ই૒਷) ׮ࣗ ࠗ઒ೠ ఋੑ दझమ

    View full-size slide

  52. “Python is dynamically typed and
    we like it that way!”
    - Guido van Rossum

    View full-size slide

  53. ۨ੉פझ౟ীࢲח
    • ఋੑ ݺदо ௏٘੄ оةࢿਸ ֫ੋ׮Ҋ ޺ਵݴ ೐۽ં౟ ҙܻ
    ࠺ਊਸ ծ୹ ࣻ ੓׮Ҋ ౸ױೞৈ بੑ೮णפ׮.

    View full-size slide

  54. ۨ੉פझ౟ীࢲח
    • ఋੑ ݺदо ௏٘੄ оةࢿਸ ֫ੋ׮Ҋ ޺ਵݴ ೐۽ં౟ ҙܻ
    ࠺ਊਸ ծ୹ ࣻ ੓׮Ҋ ౸ױೞৈ بੑ೮णפ׮.
    • नӏ ೐۽ં౟ח CI җ੿ীࢲ mypyܳ प೯೤פ׮.

    View full-size slide

  55. ۨ੉פझ౟ীࢲח
    • ఋੑ ݺदо ௏٘੄ оةࢿਸ ֫ੋ׮Ҋ ޺ਵݴ ೐۽ં౟ ҙܻ
    ࠺ਊਸ ծ୹ ࣻ ੓׮Ҋ ౸ױೞৈ بੑ೮णפ׮.
    • नӏ ೐۽ં౟ח CI җ੿ীࢲ mypyܳ प೯೤פ׮.
    • ఋੑ दझమ੄ ೠ҅۽ ੋ೧ ࠛ೙ਃೠ ௏٘ܳ ੘ࢿ೧ঠ ೡ ٸ
    ীח @typing.no_type_check

    View full-size slide

  56. ߛ௼࢟۞٘ܳ ݅٘ח ۨ੉פझ౟ীࢲ ੷൞
    ৬ ೣԋೡ ࢲߡ ূ૑פয ٜ࠙ਸ ଺Ҋ ੓
    णפ׮.
    Python, aiohttp, django

    View full-size slide

  57. Questions
    github: sunghyunzz
    email: [email protected]

    View full-size slide