SlideShare una empresa de Scribd logo
1 de 25
Descargar para leer sin conexión
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
Python e tipagem estática
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
Python e tipagem estática
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

Más contenido relacionado

La actualidad más candente

Understanding eBPF in a Hurry!
Understanding eBPF in a Hurry!Understanding eBPF in a Hurry!
Understanding eBPF in a Hurry!Ray Jenkins
 
vCenter and ESXi network port communications
vCenter and ESXi network port communicationsvCenter and ESXi network port communications
vCenter and ESXi network port communicationsAnimesh Dixit
 
Developing Microservices with Apache Camel
Developing Microservices with Apache CamelDeveloping Microservices with Apache Camel
Developing Microservices with Apache CamelClaus Ibsen
 
Hexagonal Design in Django
Hexagonal Design in DjangoHexagonal Design in Django
Hexagonal Design in Djangomvschaik
 
APEX Behind the Scenes by Scott Spendolini
APEX Behind the Scenes by Scott SpendoliniAPEX Behind the Scenes by Scott Spendolini
APEX Behind the Scenes by Scott SpendoliniEnkitec
 
We broke up with the monolith, and started dating #eventSourcing - #symfonyCat
We broke up with the monolith, and started dating #eventSourcing - #symfonyCatWe broke up with the monolith, and started dating #eventSourcing - #symfonyCat
We broke up with the monolith, and started dating #eventSourcing - #symfonyCatJavier Ferrer González
 
Performance Profiling in Rust
Performance Profiling in RustPerformance Profiling in Rust
Performance Profiling in RustInfluxData
 
Scaling up task processing with Celery
Scaling up task processing with CeleryScaling up task processing with Celery
Scaling up task processing with CeleryNicolas Grasset
 
Flask Introduction - Python Meetup
Flask Introduction - Python MeetupFlask Introduction - Python Meetup
Flask Introduction - Python MeetupAreski Belaid
 
JSP 프로그래밍 2014-2018년 기말시험 기출문제
JSP 프로그래밍 2014-2018년 기말시험 기출문제JSP 프로그래밍 2014-2018년 기말시험 기출문제
JSP 프로그래밍 2014-2018년 기말시험 기출문제Lee Sang-Ho
 
Getting started with libfabric
Getting started with libfabricGetting started with libfabric
Getting started with libfabricJianxin Xiong
 

La actualidad más candente (12)

Understanding eBPF in a Hurry!
Understanding eBPF in a Hurry!Understanding eBPF in a Hurry!
Understanding eBPF in a Hurry!
 
vCenter and ESXi network port communications
vCenter and ESXi network port communicationsvCenter and ESXi network port communications
vCenter and ESXi network port communications
 
Developing Microservices with Apache Camel
Developing Microservices with Apache CamelDeveloping Microservices with Apache Camel
Developing Microservices with Apache Camel
 
Hexagonal Design in Django
Hexagonal Design in DjangoHexagonal Design in Django
Hexagonal Design in Django
 
APEX Behind the Scenes by Scott Spendolini
APEX Behind the Scenes by Scott SpendoliniAPEX Behind the Scenes by Scott Spendolini
APEX Behind the Scenes by Scott Spendolini
 
We broke up with the monolith, and started dating #eventSourcing - #symfonyCat
We broke up with the monolith, and started dating #eventSourcing - #symfonyCatWe broke up with the monolith, and started dating #eventSourcing - #symfonyCat
We broke up with the monolith, and started dating #eventSourcing - #symfonyCat
 
PCP
PCPPCP
PCP
 
Performance Profiling in Rust
Performance Profiling in RustPerformance Profiling in Rust
Performance Profiling in Rust
 
Scaling up task processing with Celery
Scaling up task processing with CeleryScaling up task processing with Celery
Scaling up task processing with Celery
 
Flask Introduction - Python Meetup
Flask Introduction - Python MeetupFlask Introduction - Python Meetup
Flask Introduction - Python Meetup
 
JSP 프로그래밍 2014-2018년 기말시험 기출문제
JSP 프로그래밍 2014-2018년 기말시험 기출문제JSP 프로그래밍 2014-2018년 기말시험 기출문제
JSP 프로그래밍 2014-2018년 기말시험 기출문제
 
Getting started with libfabric
Getting started with libfabricGetting started with libfabric
Getting started with libfabric
 

Similar a Python e tipagem estática

Trabalho sobre a linguagem Python
Trabalho sobre a linguagem PythonTrabalho sobre a linguagem Python
Trabalho sobre a linguagem PythonRicardo Zalla
 
O Prazer De Trabalhar Com Python
O Prazer De Trabalhar Com PythonO Prazer De Trabalhar Com Python
O Prazer De Trabalhar Com PythonMarinho Brandão
 
Por que Python? Vamos Conhecer? Vamos Aprender?
Por que Python? Vamos Conhecer? Vamos Aprender?Por que Python? Vamos Conhecer? Vamos Aprender?
Por que Python? Vamos Conhecer? Vamos Aprender?Juliano Atanazio
 
Conhencendo Python e por que ela importa?
Conhencendo Python e por que ela importa?Conhencendo Python e por que ela importa?
Conhencendo Python e por que ela importa?Marcel Caraciolo
 
Porque python é legal! d
Porque python é legal!  dPorque python é legal!  d
Porque python é legal! dJoelmir Ribacki
 
Palestra Apresentando Python e Suas Aplicações
Palestra Apresentando Python e Suas AplicaçõesPalestra Apresentando Python e Suas Aplicações
Palestra Apresentando Python e Suas AplicaçõesMarcos Thomaz
 
Python No Terra (2006-12-21)
Python No Terra  (2006-12-21)Python No Terra  (2006-12-21)
Python No Terra (2006-12-21)Rudá Moura
 
Aula 01 python
Aula 01 pythonAula 01 python
Aula 01 pythonTiago
 
Introdução a linguagem Python
Introdução a linguagem PythonIntrodução a linguagem Python
Introdução a linguagem PythonLuciano Ramalho
 
A lógica do Python e seus termos
A lógica do Python e seus termosA lógica do Python e seus termos
A lógica do Python e seus termosValore I/O
 
Desenvolvimento de aplicações embarcadas utilizando Python
Desenvolvimento de aplicações embarcadas utilizando PythonDesenvolvimento de aplicações embarcadas utilizando Python
Desenvolvimento de aplicações embarcadas utilizando PythonFlávio Ribeiro
 
Comsolid2011 Introdução Python
Comsolid2011 Introdução PythonComsolid2011 Introdução Python
Comsolid2011 Introdução PythonGleison Rodrigues
 
Python Training #1, ed. 6
Python Training #1, ed. 6Python Training #1, ed. 6
Python Training #1, ed. 6Fabio Spanhol
 
Linguagem de Programação Python
Linguagem de Programação PythonLinguagem de Programação Python
Linguagem de Programação PythonJunior Sobrenome
 

Similar a Python e tipagem estática (20)

Trabalho sobre a linguagem Python
Trabalho sobre a linguagem PythonTrabalho sobre a linguagem Python
Trabalho sobre a linguagem Python
 
Dojo de Python
Dojo de PythonDojo de Python
Dojo de Python
 
Python for kids
Python for kidsPython for kids
Python for kids
 
O Prazer De Trabalhar Com Python
O Prazer De Trabalhar Com PythonO Prazer De Trabalhar Com Python
O Prazer De Trabalhar Com Python
 
Por que Python? Vamos Conhecer? Vamos Aprender?
Por que Python? Vamos Conhecer? Vamos Aprender?Por que Python? Vamos Conhecer? Vamos Aprender?
Por que Python? Vamos Conhecer? Vamos Aprender?
 
Conhencendo Python e por que ela importa?
Conhencendo Python e por que ela importa?Conhencendo Python e por que ela importa?
Conhencendo Python e por que ela importa?
 
Porque python é legal! d
Porque python é legal!  dPorque python é legal!  d
Porque python é legal! d
 
Palestra Apresentando Python e Suas Aplicações
Palestra Apresentando Python e Suas AplicaçõesPalestra Apresentando Python e Suas Aplicações
Palestra Apresentando Python e Suas Aplicações
 
Python No Terra (2006-12-21)
Python No Terra  (2006-12-21)Python No Terra  (2006-12-21)
Python No Terra (2006-12-21)
 
Aula 01 python
Aula 01 pythonAula 01 python
Aula 01 python
 
Introdução a linguagem Python
Introdução a linguagem PythonIntrodução a linguagem Python
Introdução a linguagem Python
 
Canivete suíço do Python
Canivete suíço do PythonCanivete suíço do Python
Canivete suíço do Python
 
Python, CPython, Pythonico, Cython
Python, CPython, Pythonico, CythonPython, CPython, Pythonico, Cython
Python, CPython, Pythonico, Cython
 
A lógica do Python e seus termos
A lógica do Python e seus termosA lógica do Python e seus termos
A lógica do Python e seus termos
 
Desenvolvimento de aplicações embarcadas utilizando Python
Desenvolvimento de aplicações embarcadas utilizando PythonDesenvolvimento de aplicações embarcadas utilizando Python
Desenvolvimento de aplicações embarcadas utilizando Python
 
Comsolid2011 Introdução Python
Comsolid2011 Introdução PythonComsolid2011 Introdução Python
Comsolid2011 Introdução Python
 
Introdução a linguagem Python
Introdução a linguagem PythonIntrodução a linguagem Python
Introdução a linguagem Python
 
Python-Fenalivre-Imed
Python-Fenalivre-ImedPython-Fenalivre-Imed
Python-Fenalivre-Imed
 
Python Training #1, ed. 6
Python Training #1, ed. 6Python Training #1, ed. 6
Python Training #1, ed. 6
 
Linguagem de Programação Python
Linguagem de Programação PythonLinguagem de Programação Python
Linguagem de Programação Python
 

Más de Vinta Software

Contribuir com o django é mais simples do que voce imagina!
Contribuir com o django é mais simples do que voce imagina!Contribuir com o django é mais simples do que voce imagina!
Contribuir com o django é mais simples do que voce imagina!Vinta Software
 
Django’s Club: Como fazer um sistema de assinatura
Django’s Club: Como fazer um sistema de assinaturaDjango’s Club: Como fazer um sistema de assinatura
Django’s Club: Como fazer um sistema de assinaturaVinta Software
 
5 meses de python o que aprendi
5 meses de python  o que aprendi5 meses de python  o que aprendi
5 meses de python o que aprendiVinta Software
 
Conheça como a Vinta trabalha.
Conheça como a Vinta trabalha.Conheça como a Vinta trabalha.
Conheça como a Vinta trabalha.Vinta Software
 
Vinta Software Presentation
Vinta Software PresentationVinta Software Presentation
Vinta Software PresentationVinta Software
 

Más de Vinta Software (6)

Contribuir com o django é mais simples do que voce imagina!
Contribuir com o django é mais simples do que voce imagina!Contribuir com o django é mais simples do que voce imagina!
Contribuir com o django é mais simples do que voce imagina!
 
Django’s Club: Como fazer um sistema de assinatura
Django’s Club: Como fazer um sistema de assinaturaDjango’s Club: Como fazer um sistema de assinatura
Django’s Club: Como fazer um sistema de assinatura
 
5 meses de python o que aprendi
5 meses de python  o que aprendi5 meses de python  o que aprendi
5 meses de python o que aprendi
 
Como fazer boas libs
Como fazer boas libs Como fazer boas libs
Como fazer boas libs
 
Conheça como a Vinta trabalha.
Conheça como a Vinta trabalha.Conheça como a Vinta trabalha.
Conheça como a Vinta trabalha.
 
Vinta Software Presentation
Vinta Software PresentationVinta Software Presentation
Vinta Software Presentation
 

Python e tipagem estática

  • 1. Python e Tipagem Está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
  • 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 uma linguagem dinamicamente tipada
  • 11. 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
  • 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
  • 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 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'!
  • 17. Como integrar em um 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ém de linter?
  • 21. Alguns projetos em andamento ● API Star ○ https://github.com/tomchristie/apistar ● pydantic ○ https://github.com/samuelcolvin/pydantic
  • 22. 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
  • 23. 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