blob: 2e019aa92d1d606c096495a461373f8080b59ef5 [file] [log] [blame]
Tim Peters95c99e52001-09-03 01:24:30 +00001# This contains most of the executable examples from Guido's descr
2# tutorial, once at
3#
4# http://www.python.org/2.2/descrintro.html
5#
6# A few examples left implicit in the writeup were fleshed out, a few were
7# skipped due to lack of interest (e.g., faking super() by hand isn't
8# of much interest anymore), and a few were fiddled to make the output
9# deterministic.
10
11from test_support import sortdict
12import pprint
13
14class defaultdict(dictionary):
15 def __init__(self, default=None):
16 dictionary.__init__(self)
17 self.default = default
18
19 def __getitem__(self, key):
20 try:
21 return dictionary.__getitem__(self, key)
22 except KeyError:
23 return self.default
24
25 def get(self, key, *args):
26 if not args:
27 args = (self.default,)
28 return dictionary.get(self, key, *args)
29
30 def merge(self, other):
31 for key in other:
32 if key not in self:
33 self[key] = other[key]
34
35test_1 = """
36
37Here's the new type at work:
38
39 >>> print defaultdict # show our type
Guido van Rossuma4cb7882001-09-25 03:56:29 +000040 <class 'test.test_descrtut.defaultdict'>
Tim Peters95c99e52001-09-03 01:24:30 +000041 >>> print type(defaultdict) # its metatype
42 <type 'type'>
43 >>> a = defaultdict(default=0.0) # create an instance
44 >>> print a # show the instance
45 {}
46 >>> print type(a) # show its type
Guido van Rossuma4cb7882001-09-25 03:56:29 +000047 <class 'test.test_descrtut.defaultdict'>
Tim Peters95c99e52001-09-03 01:24:30 +000048 >>> print a.__class__ # show its class
Guido van Rossuma4cb7882001-09-25 03:56:29 +000049 <class 'test.test_descrtut.defaultdict'>
Tim Peters95c99e52001-09-03 01:24:30 +000050 >>> print type(a) is a.__class__ # its type is its class
51 1
52 >>> a[1] = 3.25 # modify the instance
53 >>> print a # show the new value
54 {1: 3.25}
55 >>> print a[1] # show the new item
56 3.25
57 >>> print a[0] # a non-existant item
58 0.0
59 >>> a.merge({1:100, 2:200}) # use a dictionary method
60 >>> print sortdict(a) # show the result
61 {1: 3.25, 2: 200}
62 >>>
63
64We can also use the new type in contexts where classic only allows "real"
65dictionaries, such as the locals/globals dictionaries for the exec
66statement or the built-in function eval():
67
68 >>> def sorted(seq):
69 ... seq.sort()
70 ... return seq
71 >>> print sorted(a.keys())
72 [1, 2]
73 >>> exec "x = 3; print x" in a
74 3
75 >>> print sorted(a.keys())
76 [1, 2, '__builtins__', 'x']
77 >>> print a['x']
78 3
79 >>>
80
81However, our __getitem__() method is not used for variable access by the
82interpreter:
83
84 >>> exec "print foo" in a
85 Traceback (most recent call last):
86 File "<stdin>", line 1, in ?
87 File "<string>", line 1, in ?
88 NameError: name 'foo' is not defined
89 >>>
90
91Now I'll show that defaultdict instances have dynamic instance variables,
92just like classic classes:
93
94 >>> a.default = -1
95 >>> print a["noway"]
96 -1
97 >>> a.default = -1000
98 >>> print a["noway"]
99 -1000
Tim Peters5d2b77c2001-09-03 05:47:38 +0000100 >>> 'default' in dir(a)
101 1
Tim Peters95c99e52001-09-03 01:24:30 +0000102 >>> a.x1 = 100
103 >>> a.x2 = 200
104 >>> print a.x1
105 100
Tim Peters5d2b77c2001-09-03 05:47:38 +0000106 >>> d = dir(a)
107 >>> 'default' in d and 'x1' in d and 'x2' in d
108 1
Tim Peters95c99e52001-09-03 01:24:30 +0000109 >>> print a.__dict__
110 {'default': -1000, 'x2': 200, 'x1': 100}
111 >>>
112"""
113
114class defaultdict2(dictionary):
115 __slots__ = ['default']
116
117 def __init__(self, default=None):
118 dictionary.__init__(self)
119 self.default = default
120
121 def __getitem__(self, key):
122 try:
123 return dictionary.__getitem__(self, key)
124 except KeyError:
125 return self.default
126
127 def get(self, key, *args):
128 if not args:
129 args = (self.default,)
130 return dictionary.get(self, key, *args)
131
132 def merge(self, other):
133 for key in other:
134 if key not in self:
135 self[key] = other[key]
136
137test_2 = """
138
139The __slots__ declaration takes a list of instance variables, and reserves
140space for exactly these in the instance. When __slots__ is used, other
141instance variables cannot be assigned to:
142
143 >>> a = defaultdict2(default=0.0)
144 >>> a[1]
145 0.0
146 >>> a.default = -1
147 >>> a[1]
148 -1
149 >>> a.x1 = 1
150 Traceback (most recent call last):
151 File "<stdin>", line 1, in ?
152 AttributeError: 'defaultdict2' object has no attribute 'x1'
153 >>>
154
155"""
156
157test_3 = """
158
159Introspecting instances of built-in types
160
161For instance of built-in types, x.__class__ is now the same as type(x):
162
163 >>> type([])
164 <type 'list'>
165 >>> [].__class__
166 <type 'list'>
167 >>> list
168 <type 'list'>
169 >>> isinstance([], list)
170 1
171 >>> isinstance([], dictionary)
172 0
173 >>> isinstance([], object)
174 1
175 >>>
176
177Under the new proposal, the __methods__ attribute no longer exists:
178
179 >>> [].__methods__
180 Traceback (most recent call last):
181 File "<stdin>", line 1, in ?
182 AttributeError: 'list' object has no attribute '__methods__'
183 >>>
184
185Instead, you can get the same information from the list type:
186
187 >>> pprint.pprint(dir(list)) # like list.__dict__.keys(), but sorted
188 ['__add__',
189 '__class__',
190 '__contains__',
191 '__delattr__',
192 '__delitem__',
Guido van Rossum7b9144b2001-10-09 19:39:46 +0000193 '__delslice__',
Tim Peters95c99e52001-09-03 01:24:30 +0000194 '__eq__',
195 '__ge__',
Guido van Rossum867a8d22001-09-21 19:29:08 +0000196 '__getattribute__',
Tim Peters95c99e52001-09-03 01:24:30 +0000197 '__getitem__',
198 '__getslice__',
199 '__gt__',
200 '__hash__',
201 '__iadd__',
202 '__imul__',
203 '__init__',
204 '__le__',
205 '__len__',
206 '__lt__',
207 '__mul__',
208 '__ne__',
209 '__new__',
Guido van Rossum3926a632001-09-25 16:25:58 +0000210 '__reduce__',
Tim Peters95c99e52001-09-03 01:24:30 +0000211 '__repr__',
212 '__rmul__',
213 '__setattr__',
214 '__setitem__',
215 '__setslice__',
216 '__str__',
217 'append',
218 'count',
219 'extend',
220 'index',
221 'insert',
222 'pop',
223 'remove',
224 'reverse',
225 'sort']
226
227The new introspection API gives more information than the old one: in
228addition to the regular methods, it also shows the methods that are
229normally invoked through special notations, e.g. __iadd__ (+=), __len__
230(len), __ne__ (!=). You can invoke any method from this list directly:
231
232 >>> a = ['tic', 'tac']
233 >>> list.__len__(a) # same as len(a)
234 2
235 >>> a.__len__() # ditto
236 2
237 >>> list.append(a, 'toe') # same as a.append('toe')
238 >>> a
239 ['tic', 'tac', 'toe']
240 >>>
241
242This is just like it is for user-defined classes.
243"""
244
245test_4 = """
246
247Static methods and class methods
248
249The new introspection API makes it possible to add static methods and class
250methods. Static methods are easy to describe: they behave pretty much like
251static methods in C++ or Java. Here's an example:
252
253 >>> class C:
254 ...
255 ... def foo(x, y):
256 ... print "staticmethod", x, y
257 ... foo = staticmethod(foo)
258
259 >>> C.foo(1, 2)
260 staticmethod 1 2
261 >>> c = C()
262 >>> c.foo(1, 2)
263 staticmethod 1 2
264
265Class methods use a similar pattern to declare methods that receive an
266implicit first argument that is the *class* for which they are invoked.
267
268 >>> class C:
269 ... def foo(cls, y):
270 ... print "classmethod", cls, y
271 ... foo = classmethod(foo)
272
273 >>> C.foo(1)
Tim Peters90ba8d92001-09-09 01:21:31 +0000274 classmethod test.test_descrtut.C 1
Tim Peters95c99e52001-09-03 01:24:30 +0000275 >>> c = C()
276 >>> c.foo(1)
Tim Peters90ba8d92001-09-09 01:21:31 +0000277 classmethod test.test_descrtut.C 1
Tim Peters95c99e52001-09-03 01:24:30 +0000278
279 >>> class D(C):
280 ... pass
281
282 >>> D.foo(1)
Tim Peters90ba8d92001-09-09 01:21:31 +0000283 classmethod test.test_descrtut.D 1
Tim Peters95c99e52001-09-03 01:24:30 +0000284 >>> d = D()
285 >>> d.foo(1)
Tim Peters90ba8d92001-09-09 01:21:31 +0000286 classmethod test.test_descrtut.D 1
Tim Peters95c99e52001-09-03 01:24:30 +0000287
288This prints "classmethod __main__.D 1" both times; in other words, the
289class passed as the first argument of foo() is the class involved in the
290call, not the class involved in the definition of foo().
291
292But notice this:
293
294 >>> class E(C):
295 ... def foo(cls, y): # override C.foo
296 ... print "E.foo() called"
297 ... C.foo(y)
298 ... foo = classmethod(foo)
299
300 >>> E.foo(1)
301 E.foo() called
Tim Peters90ba8d92001-09-09 01:21:31 +0000302 classmethod test.test_descrtut.C 1
Tim Peters95c99e52001-09-03 01:24:30 +0000303 >>> e = E()
304 >>> e.foo(1)
305 E.foo() called
Tim Peters90ba8d92001-09-09 01:21:31 +0000306 classmethod test.test_descrtut.C 1
Tim Peters95c99e52001-09-03 01:24:30 +0000307
308In this example, the call to C.foo() from E.foo() will see class C as its
309first argument, not class E. This is to be expected, since the call
310specifies the class C. But it stresses the difference between these class
311methods and methods defined in metaclasses (where an upcall to a metamethod
312would pass the target class as an explicit first argument).
313"""
314
315test_5 = """
316
317Attributes defined by get/set methods
318
319
Guido van Rossum8bce4ac2001-09-06 21:56:42 +0000320 >>> class property(object):
Tim Peters95c99e52001-09-03 01:24:30 +0000321 ...
322 ... def __init__(self, get, set=None):
323 ... self.__get = get
324 ... self.__set = set
325 ...
326 ... def __get__(self, inst, type=None):
327 ... return self.__get(inst)
328 ...
329 ... def __set__(self, inst, value):
330 ... if self.__set is None:
331 ... raise AttributeError, "this attribute is read-only"
332 ... return self.__set(inst, value)
333
334Now let's define a class with an attribute x defined by a pair of methods,
335getx() and and setx():
336
337 >>> class C(object):
338 ...
339 ... def __init__(self):
340 ... self.__x = 0
341 ...
342 ... def getx(self):
343 ... return self.__x
344 ...
345 ... def setx(self, x):
346 ... if x < 0: x = 0
347 ... self.__x = x
348 ...
Guido van Rossum8bce4ac2001-09-06 21:56:42 +0000349 ... x = property(getx, setx)
Tim Peters95c99e52001-09-03 01:24:30 +0000350
351Here's a small demonstration:
352
353 >>> a = C()
354 >>> a.x = 10
355 >>> print a.x
356 10
357 >>> a.x = -10
358 >>> print a.x
359 0
360 >>>
361
Guido van Rossum8bce4ac2001-09-06 21:56:42 +0000362Hmm -- property is builtin now, so let's try it that way too.
Tim Peters95c99e52001-09-03 01:24:30 +0000363
Guido van Rossum8bce4ac2001-09-06 21:56:42 +0000364 >>> del property # unmask the builtin
365 >>> property
366 <type 'property'>
Tim Peters95c99e52001-09-03 01:24:30 +0000367
368 >>> class C(object):
369 ... def __init__(self):
370 ... self.__x = 0
371 ... def getx(self):
372 ... return self.__x
373 ... def setx(self, x):
374 ... if x < 0: x = 0
375 ... self.__x = x
Guido van Rossum8bce4ac2001-09-06 21:56:42 +0000376 ... x = property(getx, setx)
Tim Peters95c99e52001-09-03 01:24:30 +0000377
378
379 >>> a = C()
380 >>> a.x = 10
381 >>> print a.x
382 10
383 >>> a.x = -10
384 >>> print a.x
385 0
386 >>>
387"""
388
389test_6 = """
390
391Method resolution order
392
393This example is implicit in the writeup.
394
395>>> class A: # classic class
396... def save(self):
397... print "called A.save()"
398>>> class B(A):
399... pass
400>>> class C(A):
401... def save(self):
402... print "called C.save()"
403>>> class D(B, C):
404... pass
405
406>>> D().save()
407called A.save()
408
409>>> class A(object): # new class
410... def save(self):
411... print "called A.save()"
412>>> class B(A):
413... pass
414>>> class C(A):
415... def save(self):
416... print "called C.save()"
417>>> class D(B, C):
418... pass
419
420>>> D().save()
421called C.save()
422"""
423
424class A(object):
425 def m(self):
426 return "A"
427
428class B(A):
429 def m(self):
430 return "B" + super(B, self).m()
431
432class C(A):
433 def m(self):
434 return "C" + super(C, self).m()
435
436class D(C, B):
437 def m(self):
438 return "D" + super(D, self).m()
439
440
441test_7 = """
442
443Cooperative methods and "super"
444
445>>> print D().m() # "DCBA"
446DCBA
447"""
448
449test_8 = """
450
451Backwards incompatibilities
452
453>>> class A:
454... def foo(self):
455... print "called A.foo()"
456
457>>> class B(A):
458... pass
459
460>>> class C(A):
461... def foo(self):
462... B.foo(self)
463
464>>> C().foo()
465Traceback (most recent call last):
466 ...
467TypeError: unbound method foo() must be called with B instance as first argument (got C instance instead)
468
469>>> class C(A):
470... def foo(self):
471... A.foo(self)
472>>> C().foo()
473called A.foo()
474"""
475
476__test__ = {"tut1": test_1,
477 "tut2": test_2,
478 "tut3": test_3,
479 "tut4": test_4,
480 "tut5": test_5,
481 "tut6": test_6,
482 "tut7": test_7,
483 "tut8": test_8}
484
485# Magic test name that regrtest.py invokes *after* importing this module.
486# This worms around a bootstrap problem.
487# Note that doctest and regrtest both look in sys.argv for a "-v" argument,
488# so this works as expected in both ways of running regrtest.
Tim Petersa0a62222001-09-09 06:12:01 +0000489def test_main(verbose=None):
490 # Obscure: import this module as test.test_descrtut instead of as
491 # plain test_descrtut because the name of this module works its way
492 # into the doctest examples, and unless the full test.test_descrtut
493 # business is used the name can change depending on how the test is
494 # invoked.
495 import test_support, test.test_descrtut
496 test_support.run_doctest(test.test_descrtut, verbose)
Tim Peters95c99e52001-09-03 01:24:30 +0000497
498# This part isn't needed for regrtest, but for running the test directly.
499if __name__ == "__main__":
Tim Petersa0a62222001-09-09 06:12:01 +0000500 test_main(1)