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

Type Hints em Python: Pega Leve!

Type Hints em Python: Pega Leve!

As polêmicas type hints chegaram para ficar. Felizmente, desde Python 3.8 o sistema de tipos reconhece tipagem estrutural, também conhecida como "static duck typing". Graças a essa melhoria importante, não é mais preciso jogar fora toda a flexibilidade do código Pythonico ao introduzir anotações de tipos. Esta apresentação foi feita na conferência #PythonXP organizada pela Vinta Software.

Luciano Ramalho

June 22, 2020
Tweet

More Decks by Luciano Ramalho

Other Decks in Programming

Transcript

  1. 1 0 0 % o p c i o n a l
    TYPE HINTS: PEGA LEVE
    Indrodução, vantagens e desvantagens do

    sistema de tipos gradual de Python
    Luciano Ramalho
    @ramalhoorg

    View Slide

  2. 2
    https://twitter.com/raymondh/status/1255580152706158592

    View Slide

  3. TYPE HINTS?
    Breve introdução
    3

    View Slide

  4. DECLARAÇÕES DE TIPO ESTATÁTICAS
    Formalizadas na PEP 484 — Type Hints (e várias outras PEPs)
    Utilizam o módulo typing da biblioteca padrão (Python ≥ 3.5)
    Primariamente para verificadores estáticos de código-fonte, e
    não para uso em runtime.
    4
    def parse_flag(text: str) -> bool:
    return text.upper() in {'Y', 'YES', 'T', 'TRUE'}

    View Slide

  5. SOBRE TIPAGEM GRADUAL
    Tipagem Dinâmica: verificação de tipos em runtime apenas
    Ex. Lisp, Smalltalk, Python, JavaScript, Ruby, Clojure, Elixir, etc.

    Tipagem Estática: declarações de tipo no código-fonte,
    verificadas por ferramentas de análise estática do código, ou
    pelo compilador—sempre antes de executar
    Ex. C, C++, Pascal, Java, C#, Haskell, Rust, Kotlin, Swift, Elm, etc.

    Tipagem Gradual: abordagem híbrida—declarações

    de tipo estáticas, mas sem efeito em runtime

    (no runtime, o que vale é a tipagem dinâmica)
    Ex. ActionScript, Hack, Dart, TypeScript, Python com anotações de tipo, etc.
    5

    View Slide

  6. ALGUNS VERIFICADORES ESTÁTICOS DE CÓDIGO-FONTE
    Mypy
    começou na Dropbox, hoje é parte da organização Python no Github
    Pytype
    criado no Google
    Pyre
    criado no Facebook
    PyCharm
    IDE da JetBrains inclui um verificador interno
    6

    View Slide

  7. EXEMPLOS
    7

    View Slide

  8. O PRIMEIRO BUG QUE MYPY ENCONTROU PARA MIM
    8

    View Slide

  9. RESOLVIDO!
    random_queens_and_guard.py: https://tgo.li/rnd_queens
    9

    View Slide

  10. INTERPRETADOR SUBPASCAL
    Exemplo da Oficina de
    Linguagens de Programação

    no Garoa Hacker Clube
    https://tgo.li/OfLiPr2018
    10

    View Slide

  11. INTERPRETADOR SUBPASCAL: PARSER
    11

    View Slide

  12. NECESSÁRIO IMPORTAR TIPOS DO MÓDULO TYPING
    12

    View Slide

  13. NAMED TUPLE
    & DATA CLASSES
    PEP 557, Python 3.7
    13

    View Slide

  14. TYPED NAMED TUPLE
    14

    View Slide

  15. DATA CLASS
    15

    View Slide

  16. DATA CLASS COM MAIS CAMPOS
    16

    View Slide

  17. OVERLOADS
    Declarações de funções sobrecarregadas
    17

    View Slide

  18. OVERLOAD EXAMPLE #1
    18

    View Slide

  19. MAX OVERLOAD
    19

    View Slide

  20. MAX: TYPE HINTS NO TYPESHED ATÉ JUNHO/2020
    20

    View Slide

  21. MELHORIAS DEPOIS
    DO PYTHON 3.5
    21

    View Slide

  22. MELHORIAS DE USABILIDADE
    PEP 585 — Type Hinting Generics In Standard Collections
    A partir do Python 3.9 (backported to 3.7, 3.8)

    22
    from __future__ import annotations
    def loads(input: Union[str, bytes], *,
    encoding: Optional[str] = None) -> dict[str, Any]:
    ...

    View Slide

  23. STATIC DUCK TYPING
    PEP 544 — Protocols: Structural subtyping (static duck typing)
    23

    View Slide

  24. STATIC DUCK TYPING
    PEP 544 — Protocols: Structural subtyping (static duck typing)
    24

    View Slide

  25. EXEMPLO MAIS REALISTA
    25

    View Slide

  26. MAX: ANOTAÇÕES NO TYPESHED DESDE JUNHO/2020
    26

    View Slide

  27. MAX: 6 OVERLOADS PARA EXPRESSAR O DINAMISMO
    27

    View Slide

  28. VANTAGENS
    28

    View Slide

  29. VANTAGENS DAS ANOTAÇÕES DE TIPO
    Documentar assinaturas de funções
    Apoiar a IDE para verificar, completar e refatorar código
    Encontrar bugs antes de executar o programa
    Automatizar serialização/desserialização de objetos
    Sendo opcionais, evitam os problemas de sistemas de tipos
    estáticos (impossibilidade de expressar ou experimentar algo)
    29

    View Slide

  30. CUSTO
    Não existe almoço grátis
    30

    View Slide

  31. DAVID BEAZLEY NÃO CURTIU...
    https://twitter.com/dabeaz/status/981699763996450817 31

    View Slide

  32. TSUNAMI DE PEPS (MAIS AINDA: 17 PEPS ATÉ JUN/2020)
    32
    Ano PEP Título Python
    2006 3107 Function Annotations 3.0
    2014 484 Type Hints 3.5P
    483 The Theory of Type Hints N/A
    2015 482 Literature Overview for Type Hints N/A
    2016 526 Syntax for Variable Annotations 3.6
    2017 544 Protocols: Structural subtyping (static duck typing) 3.8
    557 Data Classes 3.7
    560 Core support for typing module and generic types 3.7
    561 Distributing and Packaging Type Information 3.7
    563 Postponed Evaluation of Annotations 3.7
    2018 586 Literal Types 3.8
    2019 585 Type Hinting Usability Conventions 3.8D
    589 TypedDict: Type Hints for Dicts with a Fixed Set of Keys 3.8
    591 Adding a final qualifier to typing 3.8 3.8

    View Slide

  33. DESVANTAGENS
    Esforço para aprender todo novo um conjunto de abstrações
    Generics, variância, tipagem estrutural, variáveis de tipo limitadas etc.
    Esforço para escrever as anotações
    Normalmente é fácil, mas às vezes é difícil, e pode ser impossível
    Suporte melhor em versões mais recentes de Python
    Mas também é possível anotar código de Python 2.7 com comentários, e isso
    facilita a transição
    33

    View Slide

  34. CUSTO X BENEFÍCIOS
    Os benefícios aumentam quando...
    A base de código fica grande ou muito grande
    O time é formado por devas profissionais
    Bernat Gabor* dá uma boa dica:

    se você investe em testes automatizados,

    deve investir em anotações de tipo

    * link ao final
    34

    View Slide

  35. FAQ
    Algumas respostas
    35

    View Slide

  36. PYTHON VAI VIRAR ESTATICAMENTE TIPADA COMO JAVA?
    Não.
    Seção Non-goals da PEP 484:
    36

    View Slide

  37. QUAL É O EFEITO EM RUNTIME DAS TYPE HINTS?
    Nenhum.
    O ambiente de runtime e a biblioteca padrão ignoram as type
    hints*
    Também na PEP 484:
    37
    * algumas exceções, ex.: dataclasses e functools.singledistpatch em import time

    View Slide

  38. ISSO SERVE PARA TODA PESSOA QUE USA PYTHON?
    Não.
    Usuárias de Python são muito diversas: engenheiras, analistas
    financeiras, estudantes, cientistas e pesquisadoras de quase
    todos os campos (física, biologia, sociologia, inteligência
    artificial). A análise de custo x benefício é diferente para cada
    grupo.
    Para aprender a programar ou fazer programação exploratória,
    as anotações de tipo introduzem complexidade, reduzem a
    flexibilidade do código e não agregam muito valor.
    Anotações de tipo são mais úteis em equipes de devs
    profissionais, com grandes bases de código, acostumadas a
    ferramental complexas (IDEs, test runners, CI, etc.)
    38

    View Slide

  39. REFERÊNCIAS
    Além das Lives do Eduardo Mendes!
    39

    View Slide

  40. BERNAT GABOR: THE STATE OF TYPE HINTS IN PYTHON
    https://www.bernat.tech/the-state-of-type-hints-in-python/
    40

    View Slide

  41. REAL PYTHON: PYTHON TYPE CHECKING GUIDE
    https://realpython.com/python-type-checking/
    41

    View Slide

  42. Vamos continuar o papo!
    Twitter: @ramalhoorg
    E-mail: [email protected]
    MUITO GRATO!

    View Slide