Použití správců kontextu

Writing Functions in Python

Shayne Miel

Software Architect @ Duo Security

Co je správce kontextu?

Správce kontextu:

  • Nastaví kontext
  • Spustí váš kód
  • Odstraní kontext
Writing Functions in Python

Cateringová párty

prázdná místnost

Writing Functions in Python

Cateringová párty

připravená místnost

Writing Functions in Python

Cateringová párty

párty v místnosti

Writing Functions in Python

Cateringová párty

připravená místnost

Writing Functions in Python

Cateringová párty

prázdná místnost

Writing Functions in Python

Cateringová párty jako kontext

Správci kontextu:

  • Nastaví kontext
  • Spustí váš kód
  • Odstraní kontext

Cateringová firma:

  • Připraví stoly s jídlem a pitím
  • Nechá vás a přátele slavit
  • Uklidí a odnese stoly
Writing Functions in Python

Praktický příklad

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

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

open() provede tři věci:

  • Nastaví kontext otevřením souboru
  • Umožní spustit libovolný kód nad tímto souborem
  • Odstraní kontext zavřením souboru
Writing Functions in Python

Použití správce kontextu

with
Writing Functions in Python

Použití správce kontextu

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

Použití správce kontextu

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

Použití správce kontextu

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

Použití správce kontextu

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

Použití správce kontextu

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

Použití správce kontextu

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

Lass uns üben!

Writing Functions in Python

Preparing Video For Download...