Python e Tipagem Estática
Carlos Coelho
Quem sou eu
● Carlos Coelho
○ Gama - DF/Recife - PE
○ Engenharia da Software - UnB
○ Torcedor do maior campẽao do DF Gama
○ 5 anos como desenvolvedor
@chocoelho
github.com/chocoelho
Afinal, tipagem estática,
dinâmica ou gradual?
PEPs envolvidas
● 484 - 3.5
https://www.python.org/dev/peps/pep-0484
○ Type hints
● 526 - 3.6
https://www.python.org/dev/peps/pep-0526
○ Syntax for variable annotation
● 544 - 3.7 https://www.python.org/dev/peps/pep-0544
○ Protocols
526
xpto: int # sem inicialização
xpto = 5 # passa na checagem
xpto: int = ‘a’ # linter acusa erro
# mas roda normal
sane_world: bool
if 2 + 2 == 4:
sane_world = True
else:
sane_world = False
Na prática
484
def greetings(name: str) -> str:
return “hello” + name
# funciona em Python 2 também!
def greetings(name):
# type: (str) -> str
return “hello” + name
# pode-se utilizar dicts
xpto: Dict[str, int] = {}
# ou até listas
xpto: List[int] = []
PEP 484 tl;dr
● Sintaxe padrão
● Facilita a análise estática e refatoração
● Potencial para checagem de tipos em runtime
● Notação padrão para IDEs/editores de texto
● Checagem de tipos em runtime por terceiros
PEP 526 tl;dr
● Type comments tem algumas desvantagens
○ Highlight de comentários != highlight type annotations
○ Não há como informar o tipo de uma variável indefinida, é preciso inicializá-la
com None
○ Variáveis anotadas em um condicional(if/else) podem dificultar a leitura
● Sintaxe no core da linguagem
● Sintaxe dedicada pode levar a duck-typing estático
● Type annotations != declaração de variáveis
Python continua sendo
uma linguagem
dinamicamente tipada
mypy? typing?
Benefícios
● Facilita entendimento e manutenção do código
● Facilita encontrar bugs em codebases grandes
● Melhoria em suporte para auto-complete e análise de código por
IDEs/editores de texto
● Utilizar tipagem dinâmica e estática ao mesmo tempo
[mypy]
ignore_missing_imports = True
follow_imports = skip
strict_optional = True
Exemplo de um arquivo mypy.ini localizado na raiz de um projeto X
Configurar mypy
Experiência na Vinta
Ainda não é um mar de rosas...
● Funciona em runtime, mas falha na análise estática
● Problema real:
○ Callable[[Union[bytes, bytesarray], int] e Callable[[bytes], None]
são compatíveis, mas o linter não concorda :(
■ Resolverá com PEP 544
def download_euipo_file(ftp_conn: FTP, filepath: str) ->
None:
euipo_file = BytesIO()
ftp_conn.retrbinary(“RETR {}”.format(filepath),
euipo_file.write)
Se caminha como um pato, nada como um pato e grasna como um pato,
provavelmente é um pato.
Duck Typing
class Pato:
def quack(self):
print("Quack, quack!")
def fly(self):
print("Flap, Flap!")
class Pessoa:
def quack(self):
print("I'm Quackin'!")
def fly(self):
print("I'm Flyin'!")
def na_floresta(mallard):
mallard.quack()
mallard.fly()
def main():
na_floresta(Pato())
na_floresta(Pessoa())
>>> main()
>>> Quack, quack!
>>> Flap, Flap!
>>> Quackin'!
>>> Flyin'!
Como integrar em um
editor de texto?
Linters
● Vi/Vim/NeoVim
○ Syntastic - https://github.com/vim-syntastic/syntastic
○ Neomake - https://github.com/neomake/neomake
● Sublime Text
○ SublimeLinter-contrib-mypy -
https://github.com/fredcallaway/SublimeLinter-contrib-myp
y
Linters
● Atom
○ linter-mypy - https://github.com/elarivie/linter-mypy
○ atom-mypy - https://github.com/viktor25/atom-mypy
● VSCode
○ pythonVSCode -
https://github.com/DonJayamanne/pythonVSCode
● PyCharm
○ Suporte nativo
Tem algo além de linter?
Alguns projetos em andamento
● API Star
○ https://github.com/tomchristie/apistar
● pydantic
○ https://github.com/samuelcolvin/pydantic
Outras referências
● What is Gradual Typing
○ https://wphomes.soic.indiana.edu/jsiek/what-is-gradual-typing/
● Static types in Python, oh my(py)!
○ http://blog.zulip.org/2016/10/13/static-types-in-python-oh-mypy/
● Proposal: Use mypy syntax for function annotations - BDFL
○ https://mail.python.org/pipermail/python-ideas/2014-August/02861
8.html
● Adding Optional Static Typing to Python - BDFL
○ http://www.artima.com/weblogs/viewpost.jsp?thread=85551
Outras referências
● Jukka Lehtosalo, David Fisher Static Types for Python PyCon 2017
○ https://www.youtube.com/watch?v=7ZbwZgrXnwY
● Guido van Rossum - Type Hints for Python 3.5 EuroPython 2015
○ https://www.youtube.com/watch?v=Yqnrfa5ri7E
● Pycon UK 2016: Python and static types: Let's use mypy!
○ https://www.youtube.com/watch?v=ddKQJTzgELw
● What Python can learn from Haskell? EuroPython 2014
○ http://bob.ippoli.to/python-haskell-ep2014/#/title
Slides:
bit.ly/vinta-pyne-17
Twitter: https://twitter.com/chocoelho
Github: https://github.com/chocoelho
Email: carlos@vinta.com.br

Python e tipagem estática

  • 1.
    Python e TipagemEstática Carlos Coelho
  • 2.
    Quem sou eu ●Carlos Coelho ○ Gama - DF/Recife - PE ○ Engenharia da Software - UnB ○ Torcedor do maior campẽao do DF Gama ○ 5 anos como desenvolvedor @chocoelho github.com/chocoelho
  • 4.
  • 5.
    PEPs envolvidas ● 484- 3.5 https://www.python.org/dev/peps/pep-0484 ○ Type hints ● 526 - 3.6 https://www.python.org/dev/peps/pep-0526 ○ Syntax for variable annotation ● 544 - 3.7 https://www.python.org/dev/peps/pep-0544 ○ Protocols
  • 6.
    526 xpto: int #sem inicialização xpto = 5 # passa na checagem xpto: int = ‘a’ # linter acusa erro # mas roda normal sane_world: bool if 2 + 2 == 4: sane_world = True else: sane_world = False Na prática 484 def greetings(name: str) -> str: return “hello” + name # funciona em Python 2 também! def greetings(name): # type: (str) -> str return “hello” + name # pode-se utilizar dicts xpto: Dict[str, int] = {} # ou até listas xpto: List[int] = []
  • 7.
    PEP 484 tl;dr ●Sintaxe padrão ● Facilita a análise estática e refatoração ● Potencial para checagem de tipos em runtime ● Notação padrão para IDEs/editores de texto ● Checagem de tipos em runtime por terceiros
  • 8.
    PEP 526 tl;dr ●Type comments tem algumas desvantagens ○ Highlight de comentários != highlight type annotations ○ Não há como informar o tipo de uma variável indefinida, é preciso inicializá-la com None ○ Variáveis anotadas em um condicional(if/else) podem dificultar a leitura ● Sintaxe no core da linguagem ● Sintaxe dedicada pode levar a duck-typing estático ● Type annotations != declaração de variáveis
  • 9.
    Python continua sendo umalinguagem dinamicamente tipada
  • 10.
  • 11.
    Benefícios ● Facilita entendimentoe manutenção do código ● Facilita encontrar bugs em codebases grandes ● Melhoria em suporte para auto-complete e análise de código por IDEs/editores de texto ● Utilizar tipagem dinâmica e estática ao mesmo tempo
  • 12.
    [mypy] ignore_missing_imports = True follow_imports= skip strict_optional = True Exemplo de um arquivo mypy.ini localizado na raiz de um projeto X Configurar mypy
  • 14.
  • 15.
    Ainda não éum mar de rosas... ● Funciona em runtime, mas falha na análise estática ● Problema real: ○ Callable[[Union[bytes, bytesarray], int] e Callable[[bytes], None] são compatíveis, mas o linter não concorda :( ■ Resolverá com PEP 544 def download_euipo_file(ftp_conn: FTP, filepath: str) -> None: euipo_file = BytesIO() ftp_conn.retrbinary(“RETR {}”.format(filepath), euipo_file.write)
  • 16.
    Se caminha comoum pato, nada como um pato e grasna como um pato, provavelmente é um pato. Duck Typing class Pato: def quack(self): print("Quack, quack!") def fly(self): print("Flap, Flap!") class Pessoa: def quack(self): print("I'm Quackin'!") def fly(self): print("I'm Flyin'!") def na_floresta(mallard): mallard.quack() mallard.fly() def main(): na_floresta(Pato()) na_floresta(Pessoa()) >>> main() >>> Quack, quack! >>> Flap, Flap! >>> Quackin'! >>> Flyin'!
  • 17.
    Como integrar emum editor de texto?
  • 18.
    Linters ● Vi/Vim/NeoVim ○ Syntastic- https://github.com/vim-syntastic/syntastic ○ Neomake - https://github.com/neomake/neomake ● Sublime Text ○ SublimeLinter-contrib-mypy - https://github.com/fredcallaway/SublimeLinter-contrib-myp y
  • 19.
    Linters ● Atom ○ linter-mypy- https://github.com/elarivie/linter-mypy ○ atom-mypy - https://github.com/viktor25/atom-mypy ● VSCode ○ pythonVSCode - https://github.com/DonJayamanne/pythonVSCode ● PyCharm ○ Suporte nativo
  • 20.
    Tem algo alémde linter?
  • 21.
    Alguns projetos emandamento ● API Star ○ https://github.com/tomchristie/apistar ● pydantic ○ https://github.com/samuelcolvin/pydantic
  • 22.
    Outras referências ● Whatis Gradual Typing ○ https://wphomes.soic.indiana.edu/jsiek/what-is-gradual-typing/ ● Static types in Python, oh my(py)! ○ http://blog.zulip.org/2016/10/13/static-types-in-python-oh-mypy/ ● Proposal: Use mypy syntax for function annotations - BDFL ○ https://mail.python.org/pipermail/python-ideas/2014-August/02861 8.html ● Adding Optional Static Typing to Python - BDFL ○ http://www.artima.com/weblogs/viewpost.jsp?thread=85551
  • 23.
    Outras referências ● JukkaLehtosalo, David Fisher Static Types for Python PyCon 2017 ○ https://www.youtube.com/watch?v=7ZbwZgrXnwY ● Guido van Rossum - Type Hints for Python 3.5 EuroPython 2015 ○ https://www.youtube.com/watch?v=Yqnrfa5ri7E ● Pycon UK 2016: Python and static types: Let's use mypy! ○ https://www.youtube.com/watch?v=ddKQJTzgELw ● What Python can learn from Haskell? EuroPython 2014 ○ http://bob.ippoli.to/python-haskell-ep2014/#/title
  • 24.
  • 25.