Learn the magic of writing programs that monitor, alter and react to the execution of program code by responding to imports, changes to variables, calls to functions and invocations of the builtins. This talk goes beyond the static world of metaclasses and class decorators.
Learn the magic of writing programs that monitor, alter and react to the execution of program code by responding to imports, changes to variables, calls to functions and invocations of the builtins. This talk goes beyond the static world of metaclasses and class decorators.
We'll cover how to slide a class underneath a module to intercept reads/writes, place automatic type checking over your object attributes and use stack peeking to make selected attributes private to their owning class. We'll cover import hacking, metaclasses, descriptors and decorators and graphically describe how they work internally. Source examples and color technical diagrams.
Table-of-Contents
What is Metaprogramming?
Tools At Our Disposal
Orientation Diagram: What is Metaprogramming
First Third of Talk: Import Hooking
Sample Problem #1: Subclassing an Embedded Class
A Solution to #1: Post-Import Hooking
A Solution to #1 (Packaged Up)
Alternate Solution: Pre-Import Hooking
What Does a Subclassed Module Look Like?
Some Benefits of Subclassing Modules
2nd Third of Talk: Metaclasses
Orientation Diagram: Instances, Classes and Metaclasses
Facts About Metaclasses
Example #2: Define a Class from an SQL Table Definition
Example Problem #2 (cont'd)
Metaclasses versus Class Decorators
About Meta-Inheritance
Example #3: Log the Arguments/Return Value of Method Calls
Lull After Metaclasses, Before Descriptors
Last Third of Talk: Descriptors
Python's Mechanism of Attribute Lookup
When to Use Which Lookup Mechanism
Example 4: Overriding getattr
Example 4: Using a Descriptor Instead
Python's Mechanism of Attribute Lookup (descriptors)
So What is a descriptor again?
Where are descriptors used?
Example 5: Caching an Attribute Value
Example 6: Declare an Attribute Private to a Class
Example 7: Tracking Changes in a Value
Technologist, instructor and consultant. Also transhumanist, martial artist and habitual organizer of groups and events. I pla^H^H^Hwork nights & sleep days. bio from Twitter
2:40pm Interfaces and Python by Eric Snow
Sign in to add slides, notes or videos to this session