Text
stringlengths
1
9.41k
In practice, metaclasses allow us to gain a high level of control over how a set of classes work.
This is a powerful concept, and metaclasses are not intended for most application programmers (nor, frankly, the faint of heart!). On the other hand, metaclasses open the door to a variety of coding patterns that may be difficult or impossible to achieve otherwise, and they are especially of interest to programmers se...
Although metaclasses are a core language topic and not themselves an application domain, part of this chapter’s goal is to spark your interest in exploring larger application-programming examples after you finish this book. ----- ###### To Metaclass or Not to Metaclass Metaclasses are perhaps the most advanced topi...
To borrow a quote from the comp.lang.python newsgroup by veteran Python core developer Tim Peters (who is also the author of the famous “import this” Python motto): [Metaclasses] are deeper magic than 99% of users should ever worry about.
If you wonder whether you need them, you don’t (the people who actually need them know with certainty that they need them, and don’t need an explanation about why). In other words, metaclasses are primarily intended for programmers building APIs and tools for others to use.
In many (if not most) cases, they are probably not the best choice in applications work. This is especially true if you’re developing code that other people will use in the future.
Coding something “because it seems cool” is not generally a reasonable justification, unless you are experimenting or learning. Still, metaclasses have a wide variety of potential roles, and it’s important to know when they can be useful.
For example, they can be used to enhance classes with features like tracing, object persistence, exception logging, and more.
They can also be used to construct portions of a class at runtime based upon configuration files, apply function decorators to every method of a class generically, verify conformance to expected interfaces, and so on. In their more grandiose incarnations, metaclasses can even be used to implement alternative coding pa...
Although there are often alternative ways to achieve such results (as we’ll see, the roles of class decorators and metaclasses often intersect), metaclasses provide a formal model tailored to those tasks.
We don’t have space to explore all such applications first-hand in this chapter but you should feel free to search the Web for additional use cases after studying the basics here. Probably the reason for studying metaclasses most relevant to this book is that this topic can help demystify Python’s class mechanics in g...
Although you may or may not code or reuse them in your work, a cursory understanding of metaclasses can impart a deeper understanding of Python at large. ###### Increasing Levels of Magic Most of this book has focused on straightforward application-coding techniques, as most programmers spend their time writing modul...
They may use classes and make instances, and might even do a bit of operator overloading, but they probably won’t get too deep into the details of how their classes actually work. **|** ----- However, in this book we’ve also seen a variety of tools that allow us to control Python’s behavior in generic ways, and tha...
They are run automatically in response to built-in operations and allow classes to conform to expected interfaces. _Attribute interception methods_ A special category of operator overloading methods provide a way to intercept attribute accesses on instances generically: `__getattr__,` `__setattr__, and` ``` __getattr...
They allow any number of attributes of an object—either selected attributes, or all of them—to be computed when accessed. _Class properties_ The property built-in allows us to associate code with a specific class attribute that is automatically run when the attribute is fetched, assigned, or deleted.
Though not as generic as the prior paragraph’s tools, properties allow for automatic code invocation on access to specific attributes. _Class attribute descriptors_ Really, property is a succinct way to define an attribute descriptor that runs functions on access automatically.
Descriptors allow us to code in a separate class ``` __get__, __set__, and __delete__ handler methods that are run automatically when ``` an attribute assigned to an instance of that class is accessed.
They provide a general way to insert automatically run code when a specific attribute is accessed, and they are triggered after an attribute is looked up normally. _Function and class decorators_ As we saw in Chapter 38, the special @callable syntax for decorators allows us to add logic to be automatically run when a f...
This wrapper logic can trace or time calls, validate arguments, manage all instances of a class, augment instances with extra behavior such as attribute fetch validation, and more.
Decorator syntax inserts name-rebinding logic to be run at the end of function and class definition statements—decorated function and class names are rebound to callable objects that intercept later calls. **|** ----- As mentioned in this chapter’s introduction, _metaclasses are a continuation of this_ story—they a...
This logic doesn’t rebind the class name to a decorator callable, but rather routes creation of the class itself to specialized logic. In other words, metaclasses are ultimately just another way to define automatically run _code.
Via metaclasses and the other tools just listed, Python provides ways for us to_ interject logic in a variety of contexts—at operator evaluation, attribute access, function calls, class instance creation, and now class object creation. Unlike class decorators, which usually add logic to be run at instance creation tim...
Because we can control how classes are made (and by proxy the behavior their instances acquire), their applicability is potentially very wide. As we’ve also seen, many of these advanced Python tools have intersecting roles.
For example, attributes can often be managed with properties, descriptors, or attribute interception methods.
As we’ll see in this chapter, class decorators and metaclasses can often be used interchangeably as well.
Although class decorators are often used to manage instances, they can be used to manage classes instead; similarly, while metaclasses are designed to augment class construction, they can often insert code to manage instances, too.
Since the choice of which technique to use is sometimes purely subjective, knowledge of the alternatives can help you pick the right tool for a given task. ###### The Downside of “Helper” Functions Also like the decorators of the prior chapter, metaclasses are often optional, from a theoretical perspective.
We can usually achieve the same effect by passing class objects through manager functions (sometimes known as “helper” functions), much as we can achieve the goals of decorators by passing functions and instances through manager code.
Just like decorators, though, metaclasses: - Provide a more formal and explicit structure - Help ensure that application programmers won’t forget to augment their classes according to an API’s requirements - Avoid code redundancy and its associated maintenance costs by factoring class customization logic into a s...
In that case, we can simply code the method in a superclass and have all the classes in question inherit from it: ``` class Extras: def extra(self, args): # Normal inheritance: too static ... class Client1(Extras): ...
# Clients inherit extra methods class Client2(Extras): ... class Client3(Extras): ... X = Client1() # Make an instance X.extra() # Run the extra methods ``` Sometimes, though, it’s impossible to predict such augmentation when classes are coded.
Consider the case where classes are augmented in response to choices made in a user interface at runtime, or to specifications typed in a configuration file.
Although we could code every class in our imaginary set to manually check these, too, it’s a lot to ask of clients (required is abstract here—it’s something to be filled in): ``` def extra(self, arg): ... class Client1: ...
# Client augments: too distributed if required(): Client1.extra = extra class Client2: ... if required(): Client2.extra = extra class Client3: ... if required(): Client3.extra = extra X = Client1() X.extra() ``` We can add methods to a class after the class statement like this because a class...
Although this works, it puts all the burden of augmentation on client ``` classes (and assumes they’ll remember to do this at all!). It would be better from a maintenance perspective to isolate the choice logic in a single place.
We might encapsulate some of this extra work by routing classes though a _manager function—such a manager function would extend the class as required and_ handle all the work of runtime testing and configuration: ``` def extra(self, arg): ... def extras(Class): # Manager function: too manual if requir...
It would be better if there were a simple way to enforce the augmentation in the subject classes, so that they don’t need to deal with and can’t forget to use the augmentation.
In other words, we’d like to be able to insert some code to run automatically at the end of a class statement, to augment the class. This is exactly what metaclasses do—by declaring a metaclass, we tell Python to route the creation of the class object to another class we provide: ``` def extra(self, arg): ... clas...
# Metaclass declaration only class Client2(metaclass=Extras): ...
# Client class is instance of meta class Client3(metaclass=Extras): ... X = Client1() # X is instance of Client1 X.extra() ``` Because Python invokes the metaclass automatically at the end of the class statement when the new class is created, it can augment, register, or otherwise manage the class a...
Moreover, the only requirement for the client classes is that they declare the metaclass; every class that does so will automatically acquire whatever augmentation the metaclass provides, both now and in the future if the metaclass changes.
Although it may be difficult to see in this small example, metaclasses generally handle such tasks better than other approaches. ###### Metaclasses Versus Class Decorators: Round 1 Having said that, it’s also interesting to note that the class decorators described in the preceding chapter sometimes overlap with metac...
Although they are typically used for managing or augmenting instances, class decorators can also augment classes, independent of any created instances. **|** ----- For example, suppose we coded our manager function to return the augmented class, instead of simply modifying it in-place.
This would allow a greater degree of flexibility, because the manager would be free to return any type of object that implements the class’s expected interface: ``` def extra(self, arg): ... def extras(Class): if required(): Class.extra = extra return Class class Client1: ... Client1 = extras(Clie...
In the prior chapter we presented class decorators as a tool for augmenting instance creation calls.
Because they work by automatically rebinding a class name to the result of a function, though, there’s no reason that we can’t use them to augment the class before any instances are ever created.
That is, class decorators can apply extra logic to _classes, not just instances, at creation time:_ ``` def extra(self, arg): ... def extras(Class): if required(): Class.extra = extra return Class @extras class Client1: ...
# Client1 = extras(Client1) @extras class Client2: ...
# Rebinds class independent of instances @extras class Client3: ... X = Client1() # Makes instance of augmented class X.extra() # X is instance of original Client1 ``` Decorators essentially automate the prior example’s manual name rebinding here.
Just like with metaclasses, because the decorator returns the original class, instances are **|** ----- made from it, not from a wrapper object.
In fact, instance creation is not intercepted at all. In this specific case—adding methods to a class when it’s created—the choice between metaclasses and decorators is somewhat arbitrary.
Decorators can be used to manage _both instances and classes, and they intersect with metaclasses in the second of these_ roles. However, this really addresses only one operational mode of metaclasses.
As we’ll see, decorators correspond to metaclass __init__ methods in this role, but metaclasses have additional customization hooks.
As we’ll also see, in addition to class initialization, metaclasses can perform arbitrary construction tasks that might be more difficult with decorators. Moreover, although decorators can manage both instances and classes, the converse is not as direct—metaclasses are designed to manage classes, and applying them to ...
We’ll explore this difference in code later in this chapter. Much of this section’s code has been abstract, but we’ll flesh it out into a real working example later in this chapter.
To fully understand how metaclasses work, though, we first need to get a clearer picture of their underlying model. ###### The Metaclass Model To really understand how metaclasses do their work, you need to understand a bit more about Python’s type model and what happens at the end of a class statement. ###### Class...
As we’ve seen, instances of classes have some state information attributes of their own, but they also inherit behavioral attributes from the classes from which they are made.
The same holds true for built-in types; list instances, for example, have values of their own, but they inherit methods from the list type. While we can get a lot done with such instance objects, Python’s type model turns out to be a bit richer than I’ve formally described.
Really, there’s a hole in the model we’ve seen thus far: if instances are created from classes, what is it that creates our classes?
It turns out that classes are instances of something, too: - In Python 3.0, user-defined class objects are instances of the object named type, which is itself a class. - In Python 2.6, new-style classes inherit from object, which is a subclass of type; classic classes are instances of type and are not created from ...
You can see this for yourself at the interactive prompt.
In Python 3.0, for example: ``` C:\misc> c:\python30\python ``` `>>> type([])` _# In 3.0 list is instance of list type_ ``` <class 'list'> ``` `>>> type(type([]))` _# Type of list is type class_ ``` <class 'type'> ``` `>>> type(list)` _# Same, but with type names_ ``` <class 'type'> ``` `>>> type(type)` _# ...
In Python 3.0, though, the notion of a “type” is merged with the notion of a “class.” In fact, the two are essentially synonyms—classes are types, and types are classes.
That is: - Types are defined by classes that derive from type. - User-defined classes are instances of type classes. - User-defined classes are types that generate instances of their own. As we saw earlier, this equivalence effects code that tests the type of instances: the type of an instance is the class from ...
It also has implications for the way that classes are created that turn out to be the key to this chapter’s subject.
Because classes are normally created from a root type class by default, most programmers don’t **|** ----- need to think about this type/class equivalence.
However, it opens up new possibilities for customizing both classes and their instances. For example, classes in 3.0 (and new-style classes in 2.6) are instances of the type class, and instance objects are instances of their classes; in fact, classes now have a ``` __class__ that links to type, just as an instance has...
This works the same for both built-ins and user-defined class types in 3.0.
In fact, classes are not really a separate concept at all: they are simply user-defined types, and type itself is defined by a class. In Python 2.6, things work similarly for new-style classes derived from object, because this enables 3.0 class behavior: ``` C:\misc> c:\python26\python ``` `>>> class C(object): pas...
# classes have a class too >>> X = C() >>> type(X) <class '__main__.C'> >>> type(C) <type 'type'> >>> X.__class__ <class '__main__.C'> >>> C.__class__ <type 'type'> ``` Classic classes in 2.6 are a bit different, though—because they reflect the class model in older Python releases, they do not have a...
# classes have no class themselves >>> X = C() ``` **|** ----- ``` >>> type(X) <type 'instance'> >>> type(C) <type 'classobj'> >>> X.__class__ <class __main__.C at 0x005F85A0> >>> C.__class__ AttributeError: class C has no attribute '__class__' ###### Metaclasses Are Subclasses of Type ``` So wh...
It turns out that this is the hook that allows us to code metaclasses.
Because the notion of type is the same as class today, we can subclass type with normal object-oriented techniques and class syntax to customize it.
And because classes are really instances of the `type class,` creating classes from customized subclasses of type allows us to implement custom kinds of classes.
In full detail, this all works out quite naturally—in 3.0, and in 2.6 newstyle classes: - type is a class that generates user-defined classes. - Metaclasses are subclasses of the type class. - Class objects are instances of the type class, or a subclass thereof. - Instance objects are generated from a class. I...
The type from which a class is created, and of which it is an instance, is a different relationship.
The next section describes the procedure Python follows to implement this instance-of type relationship. ###### Class Statement Protocol Subclassing the type class to customize it is really only half of the magic behind metaclasses.
We still need to somehow route a class’s creation to the metaclass, instead of the default type.
To fully understand how this is arranged, we also need to know how class statements do their business. We’ve already learned that when Python reaches a class statement, it runs its nested block of code to create its attributes—all the names assigned at the top level of the nested code block generate attributes in the ...
These names are **|** ----- usually method functions created by nested `defs, but they can also be arbitrary at-` tributes assigned to create class data shared by all instances. Technically speaking, Python follows a standard protocol to make this happen: at the _end of a_ `class` _statement, and after running all...
As we’ll see in a moment, these are the hooks that metaclass subclasses of type generally use to customize classes. For example, given a class definition like the following: ``` class Spam(Eggs): # Inherits from Eggs data = 1 # Class data attribute def meth(self, arg): # Class method att...
The trick lies in replacing type with a custom subclass that will intercept this call.
The next section shows how. ###### Declaring Metaclasses As we’ve just seen, classes are created by the type class by default.
To tell Python to create a class with a custom metaclass instead, you simply need to declare a metaclass to intercept the normal class creation call.
How you do so depends on which Python version you are using.
In Python 3.0, list the desired metaclass as a keyword argument in the class header: ``` class Spam(metaclass=Meta): # 3.0 and later ``` Inheritance superclasses can be listed in the header as well, before the metaclass.
In the following, for example, the new class Spam inherits from Eggs but is also an instance of and is created by Meta: ``` class Spam(Eggs, metaclass=Meta): # Other supers okay ``` **|** ----- We can get the same effect in Python 2.6, but we must specify the metaclass differently—using a class attribute in...
The object derivation is required to make this a new-style class, and this form no longer works in 3.0 as the attribute is simply ignored: ``` class spam(object): # 2.6 version (only) __metaclass__ = Meta ``` In 2.6, a module-global __metaclass__ variable is also available to link all classes in the...
This is no longer supported in 3.0, as it was intended as a temporary measure to make it easier to default to new-style classes without deriving every class from object. When declared in these ways, the call to create the class object run at the end of the ``` class statement is modified to invoke the metaclass instea...
The next section shows how we might go about coding this final piece of the metaclass puzzle. ###### Coding Metaclasses So far, we’ve seen how Python routes class creation calls to a metaclass, if one is provided.
How, though, do we actually code a metaclass that customizes type? It turns out that you already know most of the story—metaclasses are coded with normal Python class statements and semantics.
Their only substantial distinctions are that Python calls them automatically at the end of a class statement, and that they must adhere to the interface expected by the type superclass. **|** ----- ###### A Basic Metaclass Perhaps the simplest metaclass you can code is simply a subclass of `type with a` ``` __new_...
A ``` metaclass __new__ like this is run by the __call__ method inherited from type; it typically performs whatever customization is required and calls the `type superclass’s` ``` __new__ method to create and return the new class object: class Meta(type): def __new__(meta, classname, supers, classdict): ``` _# ...
When this code is run with Python 3.0, notice how the metaclass is invoked at the _end of the_ `class statement, before we ever make an instance—` metaclasses are for processing classes, and classes are for processing instances: ``` making class In MetaOne.new: ...Spam ...(<class '__main__.Eggs'>,) ...{'__mod...
Metaclasses can use both hooks to manage the class at creation time: ``` class MetaOne(type): def __new__(meta, classname, supers, classdict): print('In MetaOne.new: ', classname, supers, classdict, sep='\n...') return type.__new__(meta, classname, supers, classdict) def __init__(Class, classname,...
As we’ve learned, the class statement issues a simple call to create a class at the conclusion of its processing.
Because of this, any callable object can in principle be used as a metaclass, provided it accepts the arguments passed and returns an object compatible with the intended class. In fact, a simple object factory function will serve just as well as a class: _# A simple function can serve as a metaclass too_ ``` def Met...
The function is simply catching the call that the ``` type object’s __call__ normally intercepts by default: making class In MetaFunc: ...Spam ...(<class '__main__.Eggs'>,) ...{'__module__': '__main__', 'data': 1, 'meth': <function meth at 0x02B8B6A8>} making instance data: 1 ###### Overloading class cre...
The required protocol is a bit involved, though: _# __call__ can be redefined, metas can have metas_ ``` class SuperMeta(type): def __call__(meta, classname, supers, classdict): print('In SuperMeta.call: ', classname, supers, classdict, sep='\n...') return type.__call__(meta, classname, supers, class...
This is essentially what the type object does by default: ``` making class In SuperMeta.call: ...Spam ...(<class '__main__.Eggs'>,) ...{'__module__': '__main__', 'data': 1, 'meth': <function meth at 0x02B7BA98>} In SubMeta.new: ...Spam ...(<class '__main__.Eggs'>,) ...{'__module__': '__main__', 'data'...