Module 2 of 6, Python in Depth
Decorators and Context Managers
Wrap functions with decorators and guarantee clean-up with context managers.
module checksSign in to track
- Lessons complete-, not done
- Lesson quizzes taken-, not done
- Module Labs passed-, not done
- Module exam passed at 80%-, not done
- lessons
- 2
- quiz questions
- 24
- reading time
- 17 min
- exam length
- 15 Q
- coding exercises
- 3
Lessons
- DecoratorsWrap extra behaviour around functions without changing them: functions as objects, closures, the @ syntax, wrappers with *args and **kwargs, functools.wraps, decorators with arguments and stacking. 8 min 12 questions
- Context Managers and the with StatementGuarantee clean-up with the with statement: how __enter__ and __exit__ work, what happens on an error, writing managers as classes or with contextlib.contextmanager, and the ready-made ones in contextlib. 9 min 12 questions
Lab: write it yourself
Real Python, real checks: write your answer, press Run checks, and keep going until it passes. (1 exercises)
The Lab needs an account. Sign in or create a free ID to run these exercises.
Lab 1: Header context manager
Using @contextlib.contextmanager, create a manager bracket(name) that prints [{name}] before and [/{name}] after. Test with with bracket("AUDIT"): print("logged").
Sign in to practise
Sign in to access the interactive Python editor, write and run code checks against automated tests, use hints, and save your practice. Practice does not award XP.