Usando gerenciadores de contexto

Como escrever funções em Python

Shayne Miel

Software Architect @ Duo Security

O que é um gerenciador de contexto?

Um gerenciador de contexto:

  • Cria um contexto
  • Roda teu código
  • Remove o contexto
Como escrever funções em Python

Uma festa com buffet

sala vazia

Como escrever funções em Python

Uma festa com buffet

sala com buffet

Como escrever funções em Python

Uma festa com buffet

sala com festa

Como escrever funções em Python

Uma festa com buffet

sala com buffet

Como escrever funções em Python

Uma festa com buffet

sala vazia

Como escrever funções em Python

Festa com buffet como contexto

Gerenciadores de contexto:

  • Criam um contexto
  • Roda teu código
  • Removem o contexto

Buffet:

  • Monta mesas com comida e bebida
  • Deixa você e seus amigos curtirem a festa
  • Limpa e desmonta tudo
Como escrever funções em Python

Um exemplo real

with open('my_file.txt') as my_file:
  text = my_file.read()
  length = len(text)

print('The file is {} characters long'.format(length))

open() faz três coisas:

  • Cria um contexto abrindo um arquivo
  • Permite rodar qualquer código nesse arquivo
  • Remove o contexto fechando o arquivo
Como escrever funções em Python

Usando um gerenciador de contexto

with
Como escrever funções em Python

Usando um gerenciador de contexto

with <context-manager>()
Como escrever funções em Python

Usando um gerenciador de contexto

with <context-manager>(<args>)
Como escrever funções em Python

Usando um gerenciador de contexto

with <context-manager>(<args>):
Como escrever funções em Python

Usando um gerenciador de contexto

with <context-manager>(<args>):
  # Rode seu código aqui
  # Este código roda "dentro do contexto"
Como escrever funções em Python

Usando um gerenciador de contexto

with <context-manager>(<args>):
  # Rode seu código aqui
  # Este código roda "dentro do contexto"

# Este código roda depois que o contexto é removido
Como escrever funções em Python

Usando um gerenciador de contexto

with <context-manager>(<args>) as <variable-name>:
  # Rode seu código aqui
  # Este código roda "dentro do contexto"

# Este código roda depois que o contexto é removido
with open('my_file.txt') as my_file:
  text = my_file.read()
  length = len(text)

print('The file is {} characters long'.format(length))
Como escrever funções em Python

Vamos praticar!

Como escrever funções em Python

Preparing Video For Download...