blob: 269dc6938a5c75b45a330ef8de6b7cef8858aef2 [file] [log] [blame]
Guido van Rossum1fb071c1997-08-25 21:36:44 +00001<HTML>
2
3<HEAD>
4<TITLE>Metaprogramming in Python 1.5</TITLE>
5</HEAD>
6
7<BODY BGCOLOR="FFFFFF">
8
Guido van Rossum0cdb8871997-08-26 00:08:51 +00009<H1>Metaprogramming in Python 1.5 (DRAFT)</H1>
Guido van Rossum1fb071c1997-08-25 21:36:44 +000010
Guido van Rossum0cdb8871997-08-26 00:08:51 +000011<H4>XXX This is very much a work in progress.</H4>
Guido van Rossum1fb071c1997-08-25 21:36:44 +000012
13<P>While Python 1.5 is only out as a <A
14HREF="http://grail.cnri.reston.va.us/python/1.5a3/">restricted alpha
15release</A>, its metaprogramming feature is worth mentioning.
16
17<P>In previous Python releases (and still in 1.5), there is something
18called the ``Don Beaudry hook'', after its inventor and champion.
19This allows C extensions to provide alternate class behavior, thereby
20allowing the Python class syntax to be used to define other class-like
21entities. Don Beaudry has used this in his infamous <A
22HREF="http://maigret.cog.brown.edu/pyutil/">MESS</A> package; Jim
23Fulton has used it in his <A
24HREF="http://www.digicool.com/papers/ExtensionClass.html">Extension
25Classes</A> package. (It has also been referred to as the ``Don
26Beaudry <i>hack</i>, but that's a misnomer. There's nothing hackish
27about it -- in fact, it is rather elegant and deep, even though
28there's something dark to it.)
29
30<P>Documentation of the Don Beaudry hook has purposefully been kept
31minimal, since it is a feature of incredible power, and is easily
32abused. Basically, it checks whether the <b>type of the base
33class</b> is callable, and if so, it is called to create the new
34class.
35
36<P>Note the two indirection levels. Take a simple example:
37
38<PRE>
39class B:
40 pass
41
42class C(B):
43 pass
44</PRE>
45
46Take a look at the second class definition, and try to fathom ``the
47type of the base class is callable.''
48
49<P>(Types are not classes, by the way. See questions 4.2, 4.19 and in
50particular 6.22 in the <A
51HREF="http://grail.cnri.reston.va.us/cgi-bin/faqw.py" >Python FAQ</A>
52for more on this topic.)
53
54<P>
55
56<UL>
57
58<LI>The <b>base class</b> is B; this one's easy.<P>
59
60<LI>Since B is a class, its type is ``class''; so the <b>type of the
61base class</b> is the type ``class''. This is also known as
62types.ClassType, assuming the standard module <code>types</code> has
63been imported.<P>
64
65<LI>Now is the type ``class'' <b>callable</b>? No, because types (in
66core Python) are never callable. Classes are callable (calling a
67class creates a new instance) but types aren't.<P>
68
69</UL>
70
71<P>So our conclusion is that in our example, the type of the base
72class (of C) is not callable. So the Don Beaudry hook does not apply,
73and the default class creation mechanism is used (which is also used
74when there is no base class). In fact, the Don Beaudry hook never
75applies when using only core Python, since the type of a core object
76is never callable.
77
78<P>So what do Don and Jim do in order to use Don's hook? Write an
79extension that defines at least two new Python object types. The
80first would be the type for ``class-like'' objects usable as a base
81class, to trigger Don's hook. This type must be made callable.
82That's why we need a second type. Whether an object is callable
83depends on its type. So whether a type object is callable depends on
84<i>its</i> type, which is a <i>meta-type</i>. (In core Python there
85is only one meta-type, the type ``type'' (types.TypeType), which is
86the type of all type objects, even itself.) A new meta-type must
87be defined that makes the type of the class-like objects callable.
88(Normally, a third type would also be needed, the new ``instance''
89type, but this is not an absolute requirement -- the new class type
90could return an object of some existing type when invoked to create an
91instance.)
92
93<P>Still confused? Here's a simple device due to Don himself to
94explain metaclasses. Take a simple class definition; assume B is a
95special class that triggers Don's hook:
96
97<PRE>
98class C(B):
99 a = 1
100 b = 2
101</PRE>
102
103This can be though of as equivalent to:
104
105<PRE>
106C = type(B)('C', (B,), {'a': 1, 'b': 2})
107</PRE>
108
109If that's too dense for you, here's the same thing written out using
110temporary variables:
111
112<PRE>
113creator = type(B) # The type of the base class
114name = 'C' # The name of the new class
115bases = (B,) # A tuple containing the base class(es)
116namespace = {'a': 1, 'b': 2} # The namespace of the class statement
117C = creator(name, bases, namespace)
118</PRE>
119
120This is analogous to what happens without the Don Beaudry hook, except
121that in that case the creator function is set to the default class
122creator.
123
124<P>In either case, the creator is called with three arguments. The
125first one, <i>name</i>, is the name of the new class (as given at the
126top of the class statement). The <i>bases</i> argument is a tuple of
127base classes (a singleton tuple if there's only one base class, like
128the example). Finally, <i>namespace</i> is a dictionary containing
129the local variables collected during execution of the class statement.
130
131<P>Note that the contents of the namespace dictionary is simply
132whatever names were defined in the class statement. A little-known
133fact is that when Python executes a class statement, it enters a new
134local namespace, and all assignments and function definitions take
135place in this namespace. Thus, after executing the following class
136statement:
137
138<PRE>
139class C:
140 a = 1
141 def f(s): pass
142</PRE>
143
144the class namespace's contents would be {'a': 1, 'f': &lt;function f
145...&gt;}.
146
147<P>But enough already about Python metaprogramming in C; read the
148documentation of <A
149HREF="http://maigret.cog.brown.edu/pyutil/">MESS</A> or <A
150HREF="http://www.digicool.com/papers/ExtensionClass.html" >Extension
151Classes</A> for more information.
152
153<H2>Writing Metaclasses in Python</H2>
154
155<P>In Python 1.5, the requirement to write a C extension in order to
156engage in metaprogramming has been dropped (though you can still do
157it, of course). In addition to the check ``is the type of the base
158class callable,'' there's a check ``does the base class have a
159__class__ attribute.'' If so, it is assumed that the __class__
160attribute refers to a class.
161
162<P>Let's repeat our simple example from above:
163
164<PRE>
165class C(B):
166 a = 1
167 b = 2
168</PRE>
169
170Assuming B has a __class__ attribute, this translates into:
171
172<PRE>
173C = B.__class__('C', (B,), {'a': 1, 'b': 2})
174</PRE>
175
176This is exactly the same as before except that instead of type(B),
177B.__class__ is invoked. If you have read <A HREF=
178"http://grail.cnri.reston.va.us/cgi-bin/faqw.py?req=show&file=faq06.022.htp"
179>FAQ question 6.22</A> you will understand that while there is a big
180technical difference between type(B) and B.__class__, they play the
181same role at different abstraction levels. And perhaps at some point
182in the future they will really be the same thing (at which point you
183would be able to derive subclasses from built-in types).
184
185<P>Going back to the example, the class B.__class__ is instantiated,
186passing its constructor the same three arguments that are passed to
187the default class constructor or to an extension's metaprogramming
188code: <i>name</i>, <i>bases</i>, and <i>namespace</i>.
189
190<P>It is easy to be confused by what exactly happens when using a
191metaclass, because we lose the absolute distinction between classes
192and instances: a class is an instance of a metaclass (a
193``metainstance''), but technically (i.e. in the eyes of the python
194runtime system), the metaclass is just a class, and the metainstance
195is just an instance. At the end of the class statement, the metaclass
196whose metainstance is used as a base class is instantiated, yielding a
197second metainstance (of the same metaclass). This metainstance is
198then used as a (normal, non-meta) class; instantiation of the class
199means calling the metainstance, and this will return a real instance.
200And what class is that an instance of? Conceptually, it is of course
201an instance of our metainstance; but in most cases the Python runtime
202system will see it as an instance of a a helper class used by the
203metaclass to implement its (non-meta) instances...
204
205<P>Hopefully an example will make things clearer. Let's presume we
206have a metaclass MetaClass1. It's helper class (for non-meta
207instances) is callled HelperClass1. We now (manually) instantiate
208MetaClass1 once to get an empty special base class:
209
210<PRE>
211BaseClass1 = MetaClass1("BaseClass1", (), {})
212</PRE>
213
214We can now use BaseClass1 as a base class in a class statement:
215
216<PRE>
217class MySpecialClass(BaseClass1):
218 i = 1
219 def f(s): pass
220</PRE>
221
222At this point, MySpecialClass is defined; it is a metainstance of
223MetaClass1 just like BaseClass1, and in fact the expression
224``BaseClass1.__class__ == MySpecialClass.__class__ == MetaClass1''
225yields true.
226
227<P>We are now ready to create instances of MySpecialClass. Let's
228assume that no constructor arguments are required:
229
230<PRE>
231x = MySpecialClass()
232y = Myspecialclass()
233print x.__class__, y.__class__
234</PRE>
235
236The print statement shows that x and y are instances of HelperClass1.
237How did this happen? MySpecialClass is an instance of MetaClass1
238(``meta'' is irrelevant here); when an instance is called, its
239__call__ method is invoked, and presumably the __call__ method defined
240by MetaClass1 returns an instance of HelperClass1.
241
242<P>Now let's see how we could use metaprogramming -- what can we do
243with metaclasses that we can't easily do without them? Here's one
244idea: a metaclass could automatically insert trace calls for all
245method calls. Let's first develop a simplified example, without
246support for inheritance or other ``advanced'' Python features (we'll
247add those later).
248
249<PRE>
250import types
251
252class Tracing:
253 def __init__(self, name, bases, namespace):
254 """Create a new class."""
255 self.__name__ = name
256 self.__bases__ = bases
257 self.__namespace__ = namespace
258 def __call__(self):
259 """Create a new instance."""
260 return Instance(self)
261
262class Instance:
263 def __init__(self, klass):
264 self.__klass__ = klass
265 def __getattr__(self, name):
266 try:
267 value = self.__klass__.__namespace__[name]
268 except KeyError:
269 raise AttributeError, name
Guido van Rossum0cdb8871997-08-26 00:08:51 +0000270 if type(value) is not types.FunctionType:
Guido van Rossum1fb071c1997-08-25 21:36:44 +0000271 return value
272 return BoundMethod(value, self)
273
274class BoundMethod:
275 def __init__(self, function, instance):
276 self.function = function
277 self.instance = instance
278 def __call__(self, *args):
Guido van Rossum0cdb8871997-08-26 00:08:51 +0000279 print "calling", self.function, "for", self.instance, "with", args
Guido van Rossum1fb071c1997-08-25 21:36:44 +0000280 return apply(self.function, (self.instance,) + args)
Guido van Rossum0cdb8871997-08-26 00:08:51 +0000281
282Trace = Tracing('Trace', (), {})
283
284class MyTracedClass(Trace):
285 def method1(self, a):
286 self.a = a
287 def method2(self):
288 return self.a
289
290aninstance = MyTracedClass()
291
292aninstance.method1(10)
293
294print "the answer is %d" % aninstance.method2()
295</PRE>
296
297Confused already? The intention is to read this from top down. The
298Tracing class is the metaclass we're defining. Its structure is
299really simple.
300
301<P>
302
303<UL>
304
305<LI>The __init__ method is invoked when a new Tracing instance is
306created, e.g. the definition of class MyTracedClass later in the
307example. It simply saves the class name, base classes and namespace
308as instance variables.<P>
309
310<LI>The __call__ method is invoked when a Tracing instance is called,
311e.g. the creation of aninstance later in the example. It returns an
312instance of the class Instance, which is defined next.<P>
313
314</UL>
315
316<P>The class Instance is the class used for all instances of classes
317built using the Tracing metaclass, e.g. aninstance. It has two
318methods:
319
320<P>
321
322<UL>
323
324<LI>The __init__ method is invoked from the Tracing.__call__ method
325above to initialize a new instance. It saves the class reference as
326an instance variable. It uses a funny name because the user's
327instance variables (e.g. self.a later in the example) live in the same
328namespace.<P>
329
330<LI>The __getattr__ method is invoked whenever the user code
331references an attribute of the instance that is not an instance
332variable (nor a class variable; but except for __init__ and
333__getattr__ there are no class variables). It will be called, for
334example, when aninstance.method1 is referenced in the example, with
335self set to aninstance and name set to the string "method1".<P>
336
337</UL>
338
339<P>The __getattr__ method looks the name up in the __namespace__
340dictionary. If it isn't found, it raises an AttributeError exception.
341(In a more realistic example, it would first have to look through the
342base classes as well.) If it is found, there are two possibilities:
343it's either a function or it isn't. If it's not a function, it is
344assumed to be a class variable, and its value is returned. If it's a
345function, we have to ``wrap'' it in instance of yet another helper
346class, BoundMethod.
347
348<P>The BoundMethod class is needed to implement a familiar feature:
349when a method is defined, it has an initial argument, self, which is
350automatically bound to the relevant instance when it is called. For
351example, aninstance.method1(10) is equivalent to method1(aninstance,
35210). In the example if this call, first a temporary BoundMethod
353instance is created with the following constructor call: temp =
354BoundMethod(method1, aninstance); then this instance is called as
355temp(10). After the call, the temporary instance is discarded.
356
357<P>
358
359<UL>
360
361<LI>The __init__ method is invoked for the constructor call
362BoundMethod(method1, aninstance). It simply saves away its
363arguments.<P>
364
365<LI>The __call__ method is invoked when the bound method instance is
366called, as in temp(10). It needs to call method1(aninstance, 10).
367However, even though self.function is now method1 and self.instance is
368aninstance, it can't call self.function(self.instance, args) directly,
369because it should work regardless of the number of arguments passed.
370(For simplicity, support for keyword arguments has been omitted.)<P>
371
372</UL>
373
374<P>In order to be able to support arbitrary argument lists, the
375__call__ method first constructs a new argument tuple. Conveniently,
376because of the notation *args in __call__'s own argument list, the
377arguments to __call__ (except for self) are placed in the tuple args.
378To construct the desired argument list, we concatenate a singleton
379tuple containing the instance with the args tuple: (self.instance,) +
380args. (Note the trailing comma used to construct the singleton
381tuple.) In our example, the resulting argument tuple is (aninstance,
38210).
383
384<P>The intrinsic function apply() takes a function and an argument
385tuple and calls the function for it. In our example, we are calling
386apply(method1, (aninstance, 10)) which is equivalent to calling
387method(aninstance, 10).
388
389<P>From here on, things should come together quite easily. The output
390of the example code is something like this:
391
392<PRE>
393calling <function method1 at ae8d8> for <Instance instance at 95ab0> with (10,)
394calling <function method2 at ae900> for <Instance instance at 95ab0> with ()
395the answer is 10
396</PRE>
397
398<P>That was about the shortest meaningful example that I could come up
399with. A real tracing metaclass (for example, <A
400HREF="#Trace">Trace.py</A> discussed below) needs to be more
401complicated in two dimensions.
402
403<P>First, it needs to support more advanced Python features such as
404class variables, inheritance, __init__ methods, and keyword arguments.
405
406<P>Second, it needs to provide a more flexible way to handle the
407actual tracing information; perhaps it should be possible to write
408your own tracing function that gets called, perhaps it should be
409possible to enable and disable tracing on a per-class or per-instance
410basis, and perhaps a filter so that only interesting calls are traced;
411it should also be able to trace the return value of the call (or the
412exception it raised if an error occurs). Even the Trace.py example
413doesn't support all these features yet.
414
415<P>
416
Guido van Rossum1fb071c1997-08-25 21:36:44 +0000417<HR>
418
Guido van Rossum0cdb8871997-08-26 00:08:51 +0000419<H1>Real-life Examples</H1>
Guido van Rossum1fb071c1997-08-25 21:36:44 +0000420
Guido van Rossum0cdb8871997-08-26 00:08:51 +0000421<P>Have a look at some very preliminary examples that I coded up to
422teach myself how to use metaprogramming:
Guido van Rossum1fb071c1997-08-25 21:36:44 +0000423
424<DL>
425
426<DT><A HREF="Enum.py">Enum.py</A>
427
428<DD>This (ab)uses the class syntax as an elegant way to define
429enumerated types. The resulting classes are never instantiated --
430rather, their class attributes are the enumerated values. For
431example:
432
433<PRE>
434class Color(Enum):
435 red = 1
436 green = 2
437 blue = 3
438print Color.red
439</PRE>
440
441will print the string ``Color.red'', while ``Color.red==1'' is true,
442and ``Color.red + 1'' raise a TypeError exception.
443
444<P>
445
Guido van Rossum0cdb8871997-08-26 00:08:51 +0000446<DT><A NAME=Trace></A><A HREF="Trace.py">Trace.py</A>
Guido van Rossum1fb071c1997-08-25 21:36:44 +0000447
Guido van Rossum0cdb8871997-08-26 00:08:51 +0000448<DD>The resulting classes work much like standard
449classes, but by setting a special class or instance attribute
450__trace_output__ to point to a file, all calls to the class's methods
451are traced. It was a bit of a struggle to get this right. This
452should probably redone using the generic metaclass below.
Guido van Rossum1fb071c1997-08-25 21:36:44 +0000453
454<P>
455
456<DT><A HREF="Meta.py">Meta.py</A>
457
458<DD>A generic metaclass. This is an attempt at finding out how much
459standard class behavior can be mimicked by a metaclass. The
460preliminary answer appears to be that everything's fine as long as the
461class (or its clients) don't look at the instance's __class__
462attribute, nor at the class's __dict__ attribute. The use of
463__getattr__ internally makes the classic implementation of __getattr__
464hooks tough; we provide a similar hook _getattr_ instead.
465(__setattr__ and __delattr__ are not affected.)
466(XXX Hm. Could detect presence of __getattr__ and rename it.)
467
468<P>
469
470<DT><A HREF="Eiffel.py">Eiffel.py</A>
Guido van Rossum0cdb8871997-08-26 00:08:51 +0000471ppp
Guido van Rossum1fb071c1997-08-25 21:36:44 +0000472<DD>Uses the above generic metaclass to implement Eiffel style
473pre-conditions and post-conditions.
474
475<P>
Guido van Rossum0cdb8871997-08-26 00:08:51 +0000476
477<DT><A HREF="Synch.py">Synch.py</A>
478
479<DD>Uses the above generic metaclass to implement synchronized
480methods.
481
482<P>
483
Guido van Rossum1fb071c1997-08-25 21:36:44 +0000484</DL>
485
Guido van Rossum0cdb8871997-08-26 00:08:51 +0000486<P>A pattern seems to be emerging: almost all these uses of
487metaclasses (except for Enum, which is probably more cute than useful)
488mostly work by placing wrappers around method calls. An obvious
489problem with that is that it's not easy to combine the features of
490different metaclasses, while this would actually be quite useful: for
491example, I wouldn't mind getting a trace from the test run of the
492Synch module, and it would be interesting to add preconditions to it
493as well. This needs more research. Perhaps a metaclass could be
494provided that allows stackable wrappers...
495
Guido van Rossum1fb071c1997-08-25 21:36:44 +0000496</BODY>
497
498</HTML>