SlideShare uma empresa Scribd logo
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

Mais conteúdo relacionado

PDF
LockFree Algorithm
PDF
Python: a primeira mordida
PPTX
Design Pattern - Factory Method Pattern
PPTX
신입 SW 개발자 취업 준비
PPTX
Java script
PDF
Workshop 4: NodeJS. Express Framework & MongoDB.
PDF
[Windows via c/c++] 4장 프로세스
PPTX
KGC 2014: 클라이언트 개발자를 위한 컴퓨터 네트워크 기초 배현직
LockFree Algorithm
Python: a primeira mordida
Design Pattern - Factory Method Pattern
신입 SW 개발자 취업 준비
Java script
Workshop 4: NodeJS. Express Framework & MongoDB.
[Windows via c/c++] 4장 프로세스
KGC 2014: 클라이언트 개발자를 위한 컴퓨터 네트워크 기초 배현직

Mais procurados (20)

PPTX
07 스레드스케줄링,우선순위,그리고선호도
PPT
Visual Studio IDE
PPTX
Objective c slide I
PDF
NoSQL 위에서 MMORPG 개발하기
PDF
50 most frequently used unix linux commands (with examples)
PPTX
Coding standards for java
PPTX
Threading in C#
PPT
CROSS PLATFORM APPLICATIONS DEVELOPMENT
PPTX
NDC 11 자이언트 서버의 비밀
PPTX
KGC 2014: 분산 게임 서버 구조론
PDF
Java Training | Java Tutorial for Beginners | Java Programming | Java Certifi...
PDF
Introduction To CodeIgniter
PDF
인프콘 2022 - Rust 크로스 플랫폼 프로그래밍
PPTX
[C++ Korea] C++ 메모리 모델과 atomic 타입 연산들
PDF
Node.js and the MySQL Document Store
PDF
Reactjs workshop (1)
PDF
게임서버프로그래밍 #1 - IOCP
PDF
50 Ways To Love Your Project
PPTX
Java Introduction
PPTX
SQLite database in android
07 스레드스케줄링,우선순위,그리고선호도
Visual Studio IDE
Objective c slide I
NoSQL 위에서 MMORPG 개발하기
50 most frequently used unix linux commands (with examples)
Coding standards for java
Threading in C#
CROSS PLATFORM APPLICATIONS DEVELOPMENT
NDC 11 자이언트 서버의 비밀
KGC 2014: 분산 게임 서버 구조론
Java Training | Java Tutorial for Beginners | Java Programming | Java Certifi...
Introduction To CodeIgniter
인프콘 2022 - Rust 크로스 플랫폼 프로그래밍
[C++ Korea] C++ 메모리 모델과 atomic 타입 연산들
Node.js and the MySQL Document Store
Reactjs workshop (1)
게임서버프로그래밍 #1 - IOCP
50 Ways To Love Your Project
Java Introduction
SQLite database in android
Anúncio

Semelhante a Python e tipagem estática (20)

ODP
Mini Curso Python
PDF
Tutorial Python - 1
PDF
Python tutorial-ed3
PDF
Python Training #0.5 ed. 7
PDF
Python Training #1 - ed4
PDF
Tutorial Python ed. #2
PDF
Objetos Pythonicos - compacto
PDF
Hello, Python!
PDF
Trabalho sobre a linguagem Python
PDF
Python - Programando em alto nível
PDF
minicurso-python-getmeeting.pdf
PDF
Orientação a objetos em Python (compacto)
PDF
Introdução a linguagem Python 2.7
PDF
Implementação de Aplicações Móveis e Jogos com Python - Aula 1
PDF
Python Training #1 ed.6
PDF
Python Training #1, ed. 6
PDF
Python Training #1 - ed5
KEY
Introdução à Linguagem de programação Python
PDF
Linguagem Python
PDF
python_para_desenvolvedores.pdf
Mini Curso Python
Tutorial Python - 1
Python tutorial-ed3
Python Training #0.5 ed. 7
Python Training #1 - ed4
Tutorial Python ed. #2
Objetos Pythonicos - compacto
Hello, Python!
Trabalho sobre a linguagem Python
Python - Programando em alto nível
minicurso-python-getmeeting.pdf
Orientação a objetos em Python (compacto)
Introdução a linguagem Python 2.7
Implementação de Aplicações Móveis e Jogos com Python - Aula 1
Python Training #1 ed.6
Python Training #1, ed. 6
Python Training #1 - ed5
Introdução à Linguagem de programação Python
Linguagem Python
python_para_desenvolvedores.pdf
Anúncio

Mais de Vinta Software (6)

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

Último (19)

PDF
Apple Pippin Uma breve introdução. - David Glotz
PPTX
Informática Aplicada Informática Aplicada Plano de Ensino - estudo de caso NR...
PPTX
Programação - Linguagem C - Variáveis, Palavras Reservadas, tipos de dados, c...
PDF
Fundamentos de gerenciamento de ordens e planejamento no SAP TransportationMa...
PDF
COBITxITIL-Entenda as diferença em uso governança TI
PDF
Fullfilment AI - Forum ecommerce 2025 // Distrito e Total Express
PDF
Mergulho profundo técnico para gestão de transportes no SAP S/4HANA, S4TM6 Col14
PDF
Gestão de transportes básica no SAP S/4HANA, S4611 Col20
PDF
20250805_ServiceNow e a Arquitetura Orientada a Serviços (SOA) A Base para Ap...
PDF
Custos e liquidação no SAP Transportation Management, TM130 Col18
PPTX
Gestao-de-Bugs-em-Software-Introducao.pptxxxxxxxx
PDF
Aula04-Academia Heri- Tecnologia Geral 2025
PDF
Custos e faturamento no SAP S/4HANA Transportation Management, S4TM3 Col26
PDF
Otimizador de planejamento e execução no SAP Transportation Management, TM120...
PPTX
BANCO DE DADOS - AULAS INICIAIS-sgbd.pptx
PPTX
Aula 18 - Manipulacao De Arquivos python
PPTX
Aula16ManipulaçãoDadosssssssssssssssssssssssssssss
PDF
Processos na gestão de transportes, TM100 Col18
PPTX
Como-se-implementa-um-softwareeeeeeeeeeeeeeeeeeeeeeeee.pptx
Apple Pippin Uma breve introdução. - David Glotz
Informática Aplicada Informática Aplicada Plano de Ensino - estudo de caso NR...
Programação - Linguagem C - Variáveis, Palavras Reservadas, tipos de dados, c...
Fundamentos de gerenciamento de ordens e planejamento no SAP TransportationMa...
COBITxITIL-Entenda as diferença em uso governança TI
Fullfilment AI - Forum ecommerce 2025 // Distrito e Total Express
Mergulho profundo técnico para gestão de transportes no SAP S/4HANA, S4TM6 Col14
Gestão de transportes básica no SAP S/4HANA, S4611 Col20
20250805_ServiceNow e a Arquitetura Orientada a Serviços (SOA) A Base para Ap...
Custos e liquidação no SAP Transportation Management, TM130 Col18
Gestao-de-Bugs-em-Software-Introducao.pptxxxxxxxx
Aula04-Academia Heri- Tecnologia Geral 2025
Custos e faturamento no SAP S/4HANA Transportation Management, S4TM3 Col26
Otimizador de planejamento e execução no SAP Transportation Management, TM120...
BANCO DE DADOS - AULAS INICIAIS-sgbd.pptx
Aula 18 - Manipulacao De Arquivos python
Aula16ManipulaçãoDadosssssssssssssssssssssssssssss
Processos na gestão de transportes, TM100 Col18
Como-se-implementa-um-softwareeeeeeeeeeeeeeeeeeeeeeeee.pptx

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