Using context managers

Writing Functions in Python

Shayne Miel

Software Architect @ Duo Security

What is a context manager?

A context manager:

  • Sets up a context
  • Runs your code
  • Removes the context
Writing Functions in Python

A catered party

empty room

Writing Functions in Python

A catered party

room catered

Writing Functions in Python

A catered party

room party

Writing Functions in Python

A catered party

room catered

Writing Functions in Python

A catered party

empty room

Writing Functions in Python

Catered party as context

Context managers:

  • Set up a context
  • Run your code
  • Remove the context

Caterers:

  • Set up the tables with food and drink
  • Let you and your friends have a party
  • Cleaned up and removed the tables
Writing Functions in Python

A real-world example

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

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

open() does three things:

  • Sets up a context by opening a file
  • Lets you run any code you want on that file
  • Removes the context by closing the file
Writing Functions in Python

Using a context manager

with
Writing Functions in Python

Using a context manager

with <context-manager>()
Writing Functions in Python

Using a context manager

with <context-manager>(<args>)
Writing Functions in Python

Using a context manager

with <context-manager>(<args>):
Writing Functions in Python

Using a context manager

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

Using a context manager

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

# This code runs after the context is removed
Writing Functions in Python

Using a context manager

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))
Writing Functions in Python

Let's practice!

Writing Functions in Python

Preparing Video For Download...