Text stringlengths 1 9.41k |
|---|
Because of this, with metaclasses name lookup rules are somewhat different than what we are accustomed to.
The __call__ method, for example, is looked up in the class of an object; for metaclasses, this means the metaclass of a metaclass.
To use normal inheritance-based name lookup, we can achieve the same effect with... |
The output of the following is the same as the preceding
version, but note that __new__ and __init__ must have different names here, or else
they will run when the `SubMeta instance is created, not when it is later called as a`
metaclass:
**|**
-----
```
class SuperMeta:
def __call__(self, classname, supers, ... |
However, we’ll see
later that a simple function-based metaclass can often work much like a class decorator,
which allows the metaclasses to manage instances as well as classes.
###### Instances Versus Inheritance
Because metaclasses are specified in similar ways to inheritance superclasses, they can
be a bit confusin... |
A few key points should help summarize and clarify
the model:
- Metaclasses inherit from the type class. |
Although they have a special role,
metaclasses are coded with class statements and follow the usual OOP model in
Python. |
For example, as subclasses of `type, they can redefine the type object’s`
methods, overriding and customizing them as needed. |
Metaclasses typically redefine the type class’s __new__ and __init__ to customize class creation and initialization, but they can also redefine __call__ if they wish to catch the end-of-class
creation call directly. |
Although it’s unusual, they can even be simple functions that
return arbitrary objects, instead of type subclasses.
**|**
-----
- Metaclass declarations are inherited by subclasses. |
The metaclass=M declaration in a user-defined class is inherited by the class’s subclasses, too, so the metaclass will run for the construction of each class that inherits this specification in a
superclass chain.
- Metaclass attributes are not inherited by class instances. |
Metaclass declarations specify an instance relationship, which is not the same as inheritance. |
Because
classes are instances of metaclasses, the behavior defined in a metaclass applies to
the class, but not the class’s later instances. |
Instances obtain behavior from their
classes and superclasses, but not from any metaclasses. |
Technically, instance attribute lookups usually search only the __dict__ dictionaries of the instance and
all its classes; the metaclass is not included in inheritance lookup.
To illustrate the last two points, consider the following example:
```
class MetaOne(type):
def __new__(meta, classname, supers, classdic... |
Metaclasses like those we’ve seen here will be run automatically for
every class that declares them. |
Unlike the helper function approaches we saw earlier,
such classes will automatically acquire whatever augmentation the metaclass provides.
Moreover, changes in such augmentation only need to be coded in one place—the
metaclass—which simplifies making modifications as our needs evolve. |
Like so many
tools in Python, metaclasses ease maintenance work by eliminating redundancy. |
To
fully sample their power, though, we need to move on to some larger use-case examples.
**|**
-----
###### Example: Adding Methods to Classes
In this and the following section, we’re going to study examples of two common use
cases for metaclasses: adding methods to a class, and decorating all methods automatical... |
These are just two of the many metaclass roles, which unfortunately consume
the space we have left for this chapter; again, you should consult the Web for more
advanced applications. |
These examples are representative of metaclasses in action,
though, and they suffice to illustrate the basics.
Moreover, both give us an opportunity to contrast class decorators and metaclasses—
our first example compares metaclass- and decorator-based implementations of class
augmentation and instance wrapping, and t... |
As you’ll see, the two tools are often
interchangeable, and even complementary.
###### Manual Augmentation
Earlier in this chapter, we looked at skeleton code that augmented classes by adding
methods to them in various ways. |
As we saw, simple class-based inheritance suffices if
the extra methods are statically known when the class is coded. Composition via object
embedding can often achieve the same effect too. |
For more dynamic scenarios, though,
other techniques are sometimes required—helper functions can usually suffice, but
metaclasses provide an explicit structure and minimize the maintenance costs of
changes in the future.
Let’s put these ideas in action here with working code. |
Consider the following example
of manual class augmentation—it adds two methods to two classes, after they have
been created:
_# Extend manually - adding new methods to classes_
```
class Client1:
def __init__(self, value):
self.value = value
def spam(self):
return self.value * 2
class Client2:... |
It suffers from a potentially major downside, though: we have to repeat the
augmentation code for every class that needs these methods. |
In our case, it wasn’t too
onerous to add the two methods to both classes, but in more complex scenarios this
approach can be time-consuming and error-prone. |
If we ever forget to do this consistently, or we ever need to change the augmentation, we can run into problems.
###### Metaclass-Based Augmentation
Although manual augmentation works, in larger programs it would be better if we could
apply such changes to an entire set of classes automatically. |
That way, we’d avoid the
chance of the augmentation being botched for any given class. |
Moreover, coding the
augmentation in a single location better supports future changes—all classes in the set
will pick up changes automatically.
One way to meet this goal is to use metaclasses. |
If we code the augmentation in a
metaclass, every class that declares that metaclass will be augmented uniformly and
correctly and will automatically pick up any changes made in the future. |
The following
code demonstrates:
_# Extend with a metaclass - supports future changes better_
```
def eggsfunc(obj):
return obj.value * 4
```
**|**
-----
```
def hamfunc(obj, value):
return value + 'ham'
class Extender(type):
def __new__(meta, classname, supers, classdict):
classdict['eggs'... |
When run, this version’s
output is the same as before—we haven’t changed what the code does, we’ve just refactored it to encapsulate the augmentation more cleanly:
```
Ni!Ni!
Ni!Ni!Ni!Ni!
baconham
ni?ni?ni?ni?
baconham
```
Notice that the metaclass in this example still performs a fairly static task: adding ... |
In fact, if all we need to do is always add
the same two methods to a set of classes, we might as well code them in a normal
superclass and inherit in subclasses. |
In practice, though, the metaclass structure supports much more dynamic behavior. |
For instance, the subject class might also be configured based upon arbitrary logic at runtime:
_# Can also configure class based on runtime tests_
```
class MetaExtend(type):
def __new__(meta, classname, supers, classdict):
if sometest():
classdict['eggs'] = eggsfunc1
else:
classdict... |
This derives from the fact that:
- Class decorators rebind class names to the result of a function at the end of a
```
class statement.
```
- Metaclasses work by routing class object creation through an object at the end of
a class statement.
Although these are slightly different models, in practice they can usu... |
In fact, class decorators can be used to manage
both instances of a class and the class itself. |
While decorators can manage classes naturally, though, it’s somewhat less straightforward for metaclasses to manage instances.
Metaclasses are probably best used for class object management.
###### Decorator-based augmentation
For example, the prior section’s metaclass example, which adds methods to a class on
creati... |
Also like with metaclasses, the original
class type is retained, since no wrapper object layer is inserted. |
The output of the following is the same as that of the prior metaclass code:
_# Extend with a decorator: same as providing __init__ in a metaclass_
```
def eggsfunc(obj):
return obj.value * 4
def hamfunc(obj, value):
return value + 'ham'
def Extender(aClass):
aClass.eggs = eggsfunc # Manages... |
The converse isn’t quite so straightforward, though; metaclasses can be
used to manage instances, but only with a certain amount of magic. |
The next section
demonstrates.
###### Managing instances instead of classes
As we’ve just seen, class decorators can often serve the same class-management role as
metaclasses. |
Metaclasses can often serve the same instance-management role as decorators, too, but this is a bit more complex. |
That is:
- Class decorators can manage both classes and instances.
- Metaclasses can manage both classes and instances, but instances take extra work.
That said, certain applications may be better coded in one or the other. |
For example,
consider the following class decorator example from the prior chapter; it’s used to print
a trace message whenever any normally named attribute of a class instance is fetched:
_# Class decorator to trace external instance attribute fetches_
```
def Tracer(aClass): # On @ decorator
c... |
Metaclasses are designed explicitly to manage class object creation, and they have an interface tailored for this purpose. To use a metaclass to manage
instances, we have to rely on a bit more magic. |
The following metaclass has the same
effect and output as the prior decorator:
_# Manage instances like the prior example, but with a metaclass_
```
def Tracer(classname, supers, classdict): # On class creation call
aClass = type(classname, supers, classdict) # Make client class
class Wrapper:
... |
First, it must use a simple function instead of a
class, because type subclasses must adhere to object creation protocols. |
Second, it must
manually create the subject class by calling type manually; it needs to return an instance
wrapper, but metaclasses are also responsible for creating and returning the subject
class. |
Really, we’re using the metaclass protocol to imitate decorators in this example,
rather than vice versa; because both run at the conclusion of a class statement, in many
roles they are just variations on a theme. |
This metaclass version produces the same
output as the decorator when run live:
```
Trace: name
Bob
Trace: pay
2000
```
**|**
-----
You should study both versions of these examples for yourself to weigh their tradeoffs.
In general, though, metaclasses are probably best suited to class management, due to
the... |
The next section
concludes this chapter with one more common use case—applying operations to a
class’s methods automatically.
###### Example: Applying Decorators to Methods
As we saw in the prior section, because they are both run at the end of a class statement,
metaclasses and decorators can often be used _intercha... |
The choice between the two is arbitrary in many contexts. It’s also possible to
use them in _combination, as complementary tools. |
In this section, we’ll explore an_
example of just such a combination—applying a function decorator to all the methods
of a class.
###### Tracing with Decoration Manually
In the prior chapter we coded two function decorators, one that traced and counted all
calls made to a decorated function and another that timed su... |
They took various
forms there, some of which were applicable to both functions and methods and some
of which were not. |
The following collects both decorators’ final forms into a module
file for reuse and reference here:
_# File mytools.py: assorted decorator tools_
```
def tracer(func): # Use function, not class with __call__
calls = 0 # Else self is decorator instance only
def onCall(*args, **kwarg... |
If we want to trace every method of a class, this can
become tedious in larger programs. |
It would be better if we could somehow apply the
tracer decorator to all of a class’s methods automatically.
**|**
-----
With metaclasses, we can do exactly that—because they are run when a class is constructed, they are a natural place to add decoration wrappers to a class’s methods. |
By
scanning the class’s attribute dictionary and testing for function objects there, we can
automatically run methods through the decorator and rebind the original names to the
results. |
The effect is the same as the automatic method name rebinding of decorators,
but we can apply it more globally:
_# Metaclass that adds tracing decorator to every method of a client class_
```
from types import FunctionType
from mytools import tracer
class MetaTrace(type):
def __new__(meta, classname, supers,... |
The combination “just works,” thanks to the generality of both tools.
**|**
-----
###### Applying Any Decorator to Methods
The prior metaclass example works for just one specific function decorator—tracing.
However, it’s trivial to generalize this to apply any decorator to all the methods of a
class. |
All we have to do is add an outer scope layer to retain the desired decorator, much
like we did for decorators in the prior chapter. |
The following, for example, codes such
a generalization and then uses it to apply the tracer decorator again:
_# Metaclass factory: apply any decorator to all methods of a class_
```
from types import FunctionType
from mytools import tracer, timer
def decorateAll(decorator):
class MetaDecorate(type):
d... |
To use the timer function decorator shown earlier, for
example, we could use either of the last two header lines in the following when defining
**|**
-----
our class—the first accepts the timer’s default arguments, and the second specifies label
text:
```
class Person(metaclass=decorateAll(tracer)): # Appl... |
The following version replaces
the preceding example’s metaclass with a class decorator. It defines and uses a class
_decorator that applies a function decorator to all methods of a class. |
Although the prior_
sentence may sound more like a Zen statement than a technical description, this
all works quite naturally—Python’s decorators support arbitrary nesting and
combinations:
_# Class decorator factory: apply any decorator to all methods of a class_
```
from types import FunctionType
from mytools im... |
As for the metaclass
version, we retain the type of the original class—an instance of Person is an instance of
```
Person, not of some wrapper class. |
In fact, this class decorator deals with class creation
```
only; instance creation calls are not intercepted at all.
This distinction can matter in programs that require type testing for instances to yield
the original class, not a wrapper. |
When augmenting a class instead of an instance, class
decorators can retain the original class type. |
The class’s methods are not their original
functions because they are rebound to decorators, but this is less important in practice,
and it’s true in the metaclass alternative as well.
Also note that, like the metaclass version, this structure cannot support function decorator arguments that differ per method, but it ... |
To use this scheme to apply the timer decorator, for example, either of
the last two decoration lines in the following will suffice if coded just before our class
**|**
-----
definition—the first uses decorator argument defaults, and the second provides one
explicitly:
```
@decorateAll(tracer) # Decorate ... |
Both provide advanced but powerful ways to customize and manage both class and instance objects, because both ultimately allow you
to insert code into the class creation process. |
Although some more advanced applications may be better coded with one or the other, the way you choose or combine these
two tools in many cases is largely up to you.
###### “Optional” Language Features
I included a quote near the start of this chapter about metaclasses not being of interest
to 99% of Python programme... |
That statement
is not quite accurate, though, and not just numerically so.
The quote’s author is a friend of mine from the early days of Python, and I don’t mean
to pick on anyone unfairly. |
Moreover, I’ve often made such statements about language
feature obscurity myself—in this very book, in fact.
The problem, though, is that such statements really only apply to people who work
alone and only ever use code that they’ve written themselves. |
As soon as an “optional”
**|**
-----
**|**
-----
###### Chapter Summary
In this chapter, we studied metaclasses and explored examples of them in action.
Metaclasses allow us to tap into the class creation protocol of Python, in order to manage or augment user-defined classes. |
Because they automate this process, they can provide better solutions for API writers then manual code or helper functions; because
they encapsulate such code, they can minimize maintenance costs better than some
other approaches.
Along the way, we also saw how the roles of class decorators and metaclasses often
inter... |
Class decorators can be used to manage both class and instance objects; metaclasses can, too, although they are more directly targeted toward
classes.
Since this chapter covered an advanced topic, we’ll work through just a few quiz questions to review the basics (if you’ve made it this far in a chapter on metaclasses,... |
Because this is the last part of the book, we’ll
forego the end-of-part exercises. |
Be sure to see the appendixes that follow for pointers
on installation steps, and the solutions to the prior parts’ exercises.
Once you finish the quiz, you’ve officially reached the end of this book. |
Now that you
know Python inside and out, your next step, should you choose to take it, is to explore
the libraries, techniques, and tools available in the application domains in which you
work. |
Because Python is so widely used, you’ll find ample resources for using it in
almost any application you can think of—from GUIs, the Web, and databases to numeric programming, robotics, and system administration.
This is where Python starts to become truly fun, but this is also where this book’s story
ends, and others... |
For pointers on where to turn after this book, see the list of
recommended follow-up texts in the Preface. Good luck with your journey. |
And of
course, “Always look on the bright side of Life!”
###### Test Your Knowledge: Quiz
1. What is a metaclass?
2. How do you declare the metaclass of a class?
3. |
How do class decorators overlap with metaclasses for managing classes?
4. How do class decorators overlap with metaclasses for managing instances?
5. |
Would you rather count decorators or metaclasses amongst your weaponry? (And
please phrase your answer in terms of a popular Monty Python skit.)
**|**
-----
###### Test Your Knowledge: Answers
1. |
A metaclass is a class used to create a class. Normal classes are instances of the
```
type class by default. |
Metaclasses are usually subclasses of the type class, which
```
redefines class creation protocol methods in order to customize the class creation
call issued at the end of a `class statement; they typically redefine the methods`
```
__new__ and __init__ to tap into the class creation protocol. |
Metaclasses can also
```
be coded other ways—as simple functions, for example—but they are responsible
for making and returning an object for the new class.
2. |
In Python 3.0 and later, use a keyword argument in the `class header line:`
```
class C(metaclass=M). In Python 2.X, use a class attribute instead: __metaclass__
= M. |
In 3.0, the class header line can also name normal superclasses (a.k.a. base
```
classes) before the metaclass keyword argument.
3. |
Because both are automatically triggered at the end of a `class statement, class`
decorators and metaclasses can both be used to manage classes. |
Decorators rebind
a class name to a callable’s result and metaclasses route class creation through a
callable, but both hooks can be used for similar purposes. |
To manage classes,
decorators simply augment and return the original class objects. Metaclasses augment a class after they create it.
4. |
Because both are automatically triggered at the end of a `class statement, class`
decorators and metaclasses can both be used to manage class instances, by inserting
a wrapper object to catch instance creation calls. |
Decorators may rebind the class
name to a callable run on instance creation that retains the original class object.
Metaclasses can do the same, but they must also create the class object, so their
usage is somewhat more complex in this role.
5. |
Our chief weapon is decorators...decorators and metaclasses...metaclasses and
decorators.... Our two weapons are metaclasses and decorators...and ruthless efficiency.... |
Our _three weapons are metaclasses, decorators, and ruthless effi-_
ciency...and an almost fanatical devotion to Guido.... Our four...no....Amongst our
weapons.... |
Amongst our weaponry...are such elements as metaclasses, decorators.... |
I’ll come in again....
**|**
-----
-----
##### PART IX
## Appendixes
-----
-----
###### APPENDIX A
### Installation and Configuration
This appendix provides additional installation and configuration details as a resource
for people new to such topics.
###### Installing the Python Interpreter
Because you nee... |
Unless one is already available on your machine,
you’ll need to fetch, install, and possibly configure a recent version of Python on your
computer. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.