Chapter9 Lessons

Advanced

Metaprogramming and modern runtime behaviors. Dive into decorators, context managers, metaclasses, structural pattern matching, and template strings.

Chapter Lessons

01

Decorator

Decorators add new functionality to a function or class at runtime. This module shows how a simple "encryption" function for one string can be decorated to work with a collection of strings. Note that the decorator handles nested collections with the use of recursion.

02

Context Manager

Context managers are used to open and close resources as Python enters and exits a code block respectively. Some examples of the resources it can manage are files, database connections and sockets. In this module, we simulate how a context manager can handle open and close operations of a file-like object called StringIO.

03

Meta Class

Metaclass are used to modify a class as it is being created at runtime. This module shows how a metaclass can add database attributes and tables to "logic-free" model classes for the developer.

04

Weak Ref

Weak references are a way to help the Python interpreter remove unused data more easily. This module shows how it can be used to keep a server registry up-to-date as it explicitly sets up and implicitly tears down servers as the program enters and leaves a function scope.

05

Walrus Operator

Python 3.8

The walrus operator, also known as the assignment expression operator, allows you to assign values to variables as part of an expression. This feature was introduced in Python 3.8 through PEP 572.

06

Arg Enforcement

Python 3.8

Positional-only and keyword-only parameters allow you to enforce how arguments are passed to a function. This feature helps prevent misuse of function APIs and makes code more maintainable.

07

Dict Union

Python 3.9

Dictionary union operators (`|` and `|=`, introduced in Python 3.9 via PEP 584) provide clean syntax for merging dictionaries.

08

Pattern Matching

Python 3.10

Structural pattern matching allows you to match complex data structures against patterns and extract values in a clean, readable way. This feature is similar to switch-case statements in other languages but much more powerful.

09

Template Strings

Python 3.14

Template strings (t-strings) introduced in Python 3.14 (PEP 750).