summaryrefslogtreecommitdiffstats
path: root/Demo/metaclasses/index.html
blob: 269dc6938a5c75b45a330ef8de6b7cef8858aef2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
<HTML>

<HEAD>
<TITLE>Metaprogramming in Python 1.5</TITLE>
</HEAD>

<BODY BGCOLOR="FFFFFF">

<H1>Metaprogramming in Python 1.5 (DRAFT)</H1>

<H4>XXX This is very much a work in progress.</H4>

<P>While Python 1.5 is only out as a <A
HREF="http://grail.cnri.reston.va.us/python/1.5a3/">restricted alpha
release</A>, its metaprogramming feature is worth mentioning.

<P>In previous Python releases (and still in 1.5), there is something
called the ``Don Beaudry hook'', after its inventor and champion.
This allows C extensions to provide alternate class behavior, thereby
allowing the Python class syntax to be used to define other class-like
entities.  Don Beaudry has used this in his infamous <A
HREF="http://maigret.cog.brown.edu/pyutil/">MESS</A> package; Jim
Fulton has used it in his <A
HREF="http://www.digicool.com/papers/ExtensionClass.html">Extension
Classes</A> package.  (It has also been referred to as the ``Don
Beaudry <i>hack</i>, but that's a misnomer.  There's nothing hackish
about it -- in fact, it is rather elegant and deep, even though
there's something dark to it.)

<P>Documentation of the Don Beaudry hook has purposefully been kept
minimal, since it is a feature of incredible power, and is easily
abused.  Basically, it checks whether the <b>type of the base
class</b> is callable, and if so, it is called to create the new
class.

<P>Note the two indirection levels.  Take a simple example:

<PRE>
class B:
    pass

class C(B):
    pass
</PRE>

Take a look at the second class definition, and try to fathom ``the
type of the base class is callable.''

<P>(Types are not classes, by the way.  See questions 4.2, 4.19 and in
particular 6.22 in the <A
HREF="http://grail.cnri.reston.va.us/cgi-bin/faqw.py" >Python FAQ</A>
for more on this topic.)

<P>

<UL>

<LI>The <b>base class</b> is B; this one's easy.<P>

<LI>Since B is a class, its type is ``class''; so the <b>type of the
base class</b> is the type ``class''.  This is also known as
types.ClassType, assuming the standard module <code>types</code> has
been imported.<P>

<LI>Now is the type ``class'' <b>callable</b>?  No, because types (in
core Python) are never callable.  Classes are callable (calling a
class creates a new instance) but types aren't.<P>

</UL>

<P>So our conclusion is that in our example, the type of the base
class (of C) is not callable.  So the Don Beaudry hook does not apply,
and the default class creation mechanism is used (which is also used
when there is no base class).  In fact, the Don Beaudry hook never
applies when using only core Python, since the type of a core object
is never callable.

<P>So what do Don and Jim do in order to use Don's hook?  Write an
extension that defines at least two new Python object types.  The
first would be the type for ``class-like'' objects usable as a base
class, to trigger Don's hook.  This type must be made callable.
That's why we need a second type.  Whether an object is callable
depends on its type.  So whether a type object is callable depends on
<i>its</i> type, which is a <i>meta-type</i>.  (In core Python there
is only one meta-type, the type ``type'' (types.TypeType), which is
the type of all type objects, even itself.)  A new meta-type must
be defined that makes the type of the class-like objects callable.
(Normally, a third type would also be needed, the new ``instance''
type, but this is not an absolute requirement -- the new class type
could return an object of some existing type when invoked to create an
instance.)

<P>Still confused?  Here's a simple device due to Don himself to
explain metaclasses.  Take a simple class definition; assume B is a
special class that triggers Don's hook:

<PRE>
class C(B):
    a = 1
    b = 2
</PRE>

This can be though of as equivalent to:

<PRE>
C = type(B)('C', (B,), {'a': 1, 'b': 2})
</PRE>

If that's too dense for you, here's the same thing written out using
temporary variables:

<PRE>
creator = type(B)               # The type of the base class
name = 'C'                      # The name of the new class
bases = (B,)                    # A tuple containing the base class(es)
namespace = {'a': 1, 'b': 2}    # The namespace of the class statement
C = creator(name, bases, namespace)
</PRE>

This is analogous to what happens without the Don Beaudry hook, except
that in that case the creator function is set to the default class
creator.

<P>In either case, the creator is called with three arguments.  The
first one, <i>name</i>, is the name of the new class (as given at the
top of the class statement).  The <i>bases</i> argument is a tuple of
base classes (a singleton tuple if there's only one base class, like
the example).  Finally, <i>namespace</i> is a dictionary containing
the local variables collected during execution of the class statement.

<P>Note that the contents of the namespace dictionary is simply
whatever names were defined in the class statement.  A little-known
fact is that when Python executes a class statement, it enters a new
local namespace, and all assignments and function definitions take
place in this namespace.  Thus, after executing the following class
statement:

<PRE>
class C:
    a = 1
    def f(s): pass
</PRE>

the class namespace's contents would be {'a': 1, 'f': &lt;function f
...&gt;}.

<P>But enough already about Python metaprogramming in C; read the
documentation of <A
HREF="http://maigret.cog.brown.edu/pyutil/">MESS</A> or <A
HREF="http://www.digicool.com/papers/ExtensionClass.html" >Extension
Classes</A> for more information.

<H2>Writing Metaclasses in Python</H2>

<P>In Python 1.5, the requirement to write a C extension in order to
engage in metaprogramming has been dropped (though you can still do
it, of course).  In addition to the check ``is the type of the base
class callable,'' there's a check ``does the base class have a
__class__ attribute.''  If so, it is assumed that the __class__
attribute refers to a class.

<P>Let's repeat our simple example from above:

<PRE>
class C(B):
    a = 1
    b = 2
</PRE>

Assuming B has a __class__ attribute, this translates into:

<PRE>
C = B.__class__('C', (B,), {'a': 1, 'b': 2})
</PRE>

This is exactly the same as before except that instead of type(B),
B.__class__ is invoked.  If you have read <A HREF=
"http://grail.cnri.reston.va.us/cgi-bin/faqw.py?req=show&file=faq06.022.htp"
>FAQ question 6.22</A> you will understand that while there is a big
technical difference between type(B) and B.__class__, they play the
same role at different abstraction levels.  And perhaps at some point
in the future they will really be the same thing (at which point you
would be able to derive subclasses from built-in types).

<P>Going back to the example, the class B.__class__ is instantiated,
passing its constructor the same three arguments that are passed to
the default class constructor or to an extension's metaprogramming
code: <i>name</i>, <i>bases</i>, and <i>namespace</i>.

<P>It is easy to be confused by what exactly happens when using a
metaclass, because we lose the absolute distinction between classes
and instances: a class is an instance of a metaclass (a
``metainstance''), but technically (i.e. in the eyes of the python
runtime system), the metaclass is just a class, and the metainstance
is just an instance.  At the end of the class statement, the metaclass
whose metainstance is used as a base class is instantiated, yielding a
second metainstance (of the same metaclass).  This metainstance is
then used as a (normal, non-meta) class; instantiation of the class
means calling the metainstance, and this will return a real instance.
And what class is that an instance of?  Conceptually, it is of course
an instance of our metainstance; but in most cases the Python runtime
system will see it as an instance of a a helper class used by the
metaclass to implement its (non-meta) instances...

<P>Hopefully an example will make things clearer.  Let's presume we
have a metaclass MetaClass1.  It's helper class (for non-meta
instances) is callled HelperClass1.  We now (manually) instantiate
MetaClass1 once to get an empty special base class:

<PRE>
BaseClass1 = MetaClass1("BaseClass1", (), {})
</PRE>

We can now use BaseClass1 as a base class in a class statement:

<PRE>
class MySpecialClass(BaseClass1):
    i = 1
    def f(s): pass
</PRE>

At this point, MySpecialClass is defined; it is a metainstance of
MetaClass1 just like BaseClass1, and in fact the expression
``BaseClass1.__class__ == MySpecialClass.__class__ == MetaClass1''
yields true.

<P>We are now ready to create instances of MySpecialClass.  Let's
assume that no constructor arguments are required:

<PRE>
x = MySpecialClass()
y = Myspecialclass()
print x.__class__, y.__class__
</PRE>

The print statement shows that x and y are instances of HelperClass1.
How did this happen?  MySpecialClass is an instance of MetaClass1
(``meta'' is irrelevant here); when an instance is called, its
__call__ method is invoked, and presumably the __call__ method defined
by MetaClass1 returns an instance of HelperClass1.

<P>Now let's see how we could use metaprogramming -- what can we do
with metaclasses that we can't easily do without them?  Here's one
idea: a metaclass could automatically insert trace calls for all
method calls.  Let's first develop a simplified example, without
support for inheritance or other ``advanced'' Python features (we'll
add those later).

<PRE>
import types

class Tracing:
    def __init__(self, name, bases, namespace):
        """Create a new class."""
        self.__name__ = name
        self.__bases__ = bases
        self.__namespace__ = namespace
    def __call__(self):
        """Create a new instance."""
        return Instance(self)

class Instance:
    def __init__(self, klass):
        self.__klass__ = klass
    def __getattr__(self, name):
        try:
            value = self.__klass__.__namespace__[name]
        except KeyError:
            raise AttributeError, name
        if type(value) is not types.FunctionType:
            return value
        return BoundMethod(value, self)

class BoundMethod:
    def __init__(self, function, instance):
        self.function = function
        self.instance = instance
    def __call__(self, *args):
        print "calling", self.function, "for", self.instance, "with", args
        return apply(self.function, (self.instance,) + args)

Trace = Tracing('Trace', (), {})

class MyTracedClass(Trace):
    def method1(self, a):
        self.a = a
    def method2(self):
        return self.a

aninstance = MyTracedClass()

aninstance.method1(10)

print "the answer is %d" % aninstance.method2()
</PRE>

Confused already?  The intention is to read this from top down.  The
Tracing class is the metaclass we're defining.  Its structure is
really simple.

<P>

<UL>

<LI>The __init__ method is invoked when a new Tracing instance is
created, e.g. the definition of class MyTracedClass later in the
example.  It simply saves the class name, base classes and namespace
as instance variables.<P>

<LI>The __call__ method is invoked when a Tracing instance is called,
e.g. the creation of aninstance later in the example.  It returns an
instance of the class Instance, which is defined next.<P>

</UL>

<P>The class Instance is the class used for all instances of classes
built using the Tracing metaclass, e.g. aninstance.  It has two
methods:

<P>

<UL>

<LI>The __init__ method is invoked from the Tracing.__call__ method
above to initialize a new instance.  It saves the class reference as
an instance variable.  It uses a funny name because the user's
instance variables (e.g. self.a later in the example) live in the same
namespace.<P>

<LI>The __getattr__ method is invoked whenever the user code
references an attribute of the instance that is not an instance
variable (nor a class variable; but except for __init__ and
__getattr__ there are no class variables).  It will be called, for
example, when aninstance.method1 is referenced in the example, with
self set to aninstance and name set to the string "method1".<P>

</UL>

<P>The __getattr__ method looks the name up in the __namespace__
dictionary.  If it isn't found, it raises an AttributeError exception.
(In a more realistic example, it would first have to look through the
base classes as well.)  If it is found, there are two possibilities:
it's either a function or it isn't.  If it's not a function, it is
assumed to be a class variable, and its value is returned.  If it's a
function, we have to ``wrap'' it in instance of yet another helper
class, BoundMethod.

<P>The BoundMethod class is needed to implement a familiar feature:
when a method is defined, it has an initial argument, self, which is
automatically bound to the relevant instance when it is called.  For
example, aninstance.method1(10) is equivalent to method1(aninstance,
10).  In the example if this call, first a temporary BoundMethod
instance is created with the following constructor call: temp =
BoundMethod(method1, aninstance); then this instance is called as
temp(10).  After the call, the temporary instance is discarded.

<P>

<UL>

<LI>The __init__ method is invoked for the constructor call
BoundMethod(method1, aninstance).  It simply saves away its
arguments.<P>

<LI>The __call__ method is invoked when the bound method instance is
called, as in temp(10).  It needs to call method1(aninstance, 10).
However, even though self.function is now method1 and self.instance is
aninstance, it can't call self.function(self.instance, args) directly,
because it should work regardless of the number of arguments passed.
(For simplicity, support for keyword arguments has been omitted.)<P>

</UL>

<P>In order to be able to support arbitrary argument lists, the
__call__ method first constructs a new argument tuple.  Conveniently,
because of the notation *args in __call__'s own argument list, the
arguments to __call__ (except for self) are placed in the tuple args.
To construct the desired argument list, we concatenate a singleton
tuple containing the instance with the args tuple: (self.instance,) +
args.  (Note the trailing comma used to construct the singleton
tuple.)  In our example, the resulting argument tuple is (aninstance,
10).

<P>The intrinsic function apply() takes a function and an argument
tuple and calls the function for it.  In our example, we are calling
apply(method1, (aninstance, 10)) which is equivalent to calling
method(aninstance, 10).

<P>From here on, things should come together quite easily.  The output
of the example code is something like this:

<PRE>
calling <function method1 at ae8d8> for <Instance instance at 95ab0> with (10,)
calling <function method2 at ae900> for <Instance instance at 95ab0> with ()
the answer is 10
</PRE>

<P>That was about the shortest meaningful example that I could come up
with.  A real tracing metaclass (for example, <A
HREF="#Trace">Trace.py</A> discussed below) needs to be more
complicated in two dimensions.

<P>First, it needs to support more advanced Python features such as
class variables, inheritance, __init__ methods, and keyword arguments.

<P>Second, it needs to provide a more flexible way to handle the
actual tracing information; perhaps it should be possible to write
your own tracing function that gets called, perhaps it should be
possible to enable and disable tracing on a per-class or per-instance
basis, and perhaps a filter so that only interesting calls are traced;
it should also be able to trace the return value of the call (or the
exception it raised if an error occurs).  Even the Trace.py example
doesn't support all these features yet.

<P>

<HR>

<H1>Real-life Examples</H1>

<P>Have a look at some very preliminary examples that I coded up to
teach myself how to use metaprogramming:

<DL>

<DT><A HREF="Enum.py">Enum.py</A>

<DD>This (ab)uses the class syntax as an elegant way to define
enumerated types.  The resulting classes are never instantiated --
rather, their class attributes are the enumerated values.  For
example:

<PRE>
class Color(Enum):
    red = 1
    green = 2
    blue = 3
print Color.red
</PRE>

will print the string ``Color.red'', while ``Color.red==1'' is true,
and ``Color.red + 1'' raise a TypeError exception.

<P>

<DT><A NAME=Trace></A><A HREF="Trace.py">Trace.py</A>

<DD>The resulting classes work much like standard
classes, but by setting a special class or instance attribute
__trace_output__ to point to a file, all calls to the class's methods
are traced.  It was a bit of a struggle to get this right.  This
should probably redone using the generic metaclass below.

<P>

<DT><A HREF="Meta.py">Meta.py</A>

<DD>A generic metaclass.  This is an attempt at finding out how much
standard class behavior can be mimicked by a metaclass.  The
preliminary answer appears to be that everything's fine as long as the
class (or its clients) don't look at the instance's __class__
attribute, nor at the class's __dict__ attribute.  The use of
__getattr__ internally makes the classic implementation of __getattr__
hooks tough; we provide a similar hook _getattr_ instead.
(__setattr__ and __delattr__ are not affected.)
(XXX Hm.  Could detect presence of __getattr__ and rename it.)

<P>

<DT><A HREF="Eiffel.py">Eiffel.py</A>
ppp
<DD>Uses the above generic metaclass to implement Eiffel style
pre-conditions and post-conditions.

<P>

<DT><A HREF="Synch.py">Synch.py</A>

<DD>Uses the above generic metaclass to implement synchronized
methods.

<P>

</DL>

<P>A pattern seems to be emerging: almost all these uses of
metaclasses (except for Enum, which is probably more cute than useful)
mostly work by placing wrappers around method calls.  An obvious
problem with that is that it's not easy to combine the features of
different metaclasses, while this would actually be quite useful: for
example, I wouldn't mind getting a trace from the test run of the
Synch module, and it would be interesting to add preconditions to it
as well.  This needs more research.  Perhaps a metaclass could be
provided that allows stackable wrappers...

</BODY>

</HTML>