Uso de gestores de contexto

Escribir funciones en Python

Shayne Miel

Software Architect @ Duo Security

¿Qué es un gestor de contexto?

Un gestor de contexto:

  • Crea un contexto
  • Ejecuta tu código
  • Quita el contexto
Escribir funciones en Python

Un catering

sala vacía

Escribir funciones en Python

Un catering

sala con catering

Escribir funciones en Python

Un catering

fiesta en la sala

Escribir funciones en Python

Un catering

sala con catering

Escribir funciones en Python

Un catering

sala vacía

Escribir funciones en Python

Catering como contexto

Los gestores de contexto:

  • Crean un contexto
  • Ejecutan tu código
  • Quiten el contexto

Los caterings:

  • Montan mesas con comida y bebida
  • Te dejan celebrar la fiesta
  • Recogen y quitan las mesas
Escribir funciones en Python

Un ejemplo 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() hace tres cosas:

  • Crea un contexto al abrir un archivo
  • Te deja ejecutar código sobre ese archivo
  • Quita el contexto al cerrar el archivo
Escribir funciones en Python

Usar un gestor de contexto

with
Escribir funciones en Python

Usar un gestor de contexto

with <context-manager>()
Escribir funciones en Python

Usar un gestor de contexto

with <context-manager>(<args>)
Escribir funciones en Python

Usar un gestor de contexto

with <context-manager>(<args>):
Escribir funciones en Python

Usar un gestor de contexto

with <context-manager>(<args>):
  # Run your code here
  # This code is running "inside the context"
Escribir funciones en Python

Usar un gestor de contexto

with <context-manager>(<args>):
  # Run your code here
  # This code is running "inside the context"

# This code runs after the context is removed
Escribir funciones en Python

Usar un gestor de contexto

with <context-manager>(<args>) as <variable-name>:
  # Run your code here
  # This code is running "inside the context"

# This code runs after the context is removed
with open('my_file.txt') as my_file:
  text = my_file.read()
  length = len(text)

print('The file is {} characters long'.format(length))
Escribir funciones en Python

¡Vamos a practicar!

Escribir funciones en Python

Preparing Video For Download...