blob: 80e7f05e0e564fd66d26751d83714950e3beb574 [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__',
193 '__eq__',
194 '__ge__',
Guido van Rossum867a8d22001-09-21 19:29:08 +0000195 '__getattribute__',
Tim Peters95c99e52001-09-03 01:24:30 +0000196 '__getitem__',
197 '__getslice__',
198 '__gt__',
199 '__hash__',
200 '__iadd__',
201 '__imul__',
202 '__init__',
203 '__le__',
204 '__len__',
205 '__lt__',
206 '__mul__',
207 '__ne__',
208 '__new__',
Guido van Rossum3926a632001-09-25 16:25:58 +0000209 '__reduce__',
Tim Peters95c99e52001-09-03 01:24:30 +0000210 '__repr__',
211 '__rmul__',
212 '__setattr__',
213 '__setitem__',
214 '__setslice__',
215 '__str__',
216 'append',
217 'count',
218 'extend',
219 'index',
220 'insert',
221 'pop',
222 'remove',
223 'reverse',
224 'sort']
225
226The new introspection API gives more information than the old one: in
227addition to the regular methods, it also shows the methods that are
228normally invoked through special notations, e.g. __iadd__ (+=), __len__
229(len), __ne__ (!=). You can invoke any method from this list directly:
230
231 >>> a = ['tic', 'tac']
232 >>> list.__len__(a) # same as len(a)
233 2
234 >>> a.__len__() # ditto
235 2
236 >>> list.append(a, 'toe') # same as a.append('toe')
237 >>> a
238 ['tic', 'tac', 'toe']
239 >>>
240
241This is just like it is for user-defined classes.
242"""
243
244test_4 = """
245
246Static methods and class methods
247
248The new introspection API makes it possible to add static methods and class
249methods. Static methods are easy to describe: they behave pretty much like
250static methods in C++ or Java. Here's an example:
251
252 >>> class C:
253 ...
254 ... def foo(x, y):
255 ... print "staticmethod", x, y
256 ... foo = staticmethod(foo)
257
258 >>> C.foo(1, 2)
259 staticmethod 1 2
260 >>> c = C()
261 >>> c.foo(1, 2)
262 staticmethod 1 2
263
264Class methods use a similar pattern to declare methods that receive an
265implicit first argument that is the *class* for which they are invoked.
266
267 >>> class C:
268 ... def foo(cls, y):
269 ... print "classmethod", cls, y
270 ... foo = classmethod(foo)
271
272 >>> C.foo(1)
Tim Peters90ba8d92001-09-09 01:21:31 +0000273 classmethod test.test_descrtut.C 1
Tim Peters95c99e52001-09-03 01:24:30 +0000274 >>> c = C()
275 >>> c.foo(1)
Tim Peters90ba8d92001-09-09 01:21:31 +0000276 classmethod test.test_descrtut.C 1
Tim Peters95c99e52001-09-03 01:24:30 +0000277
278 >>> class D(C):
279 ... pass
280
281 >>> D.foo(1)
Tim Peters90ba8d92001-09-09 01:21:31 +0000282 classmethod test.test_descrtut.D 1
Tim Peters95c99e52001-09-03 01:24:30 +0000283 >>> d = D()
284 >>> d.foo(1)
Tim Peters90ba8d92001-09-09 01:21:31 +0000285 classmethod test.test_descrtut.D 1
Tim Peters95c99e52001-09-03 01:24:30 +0000286
287This prints "classmethod __main__.D 1" both times; in other words, the
288class passed as the first argument of foo() is the class involved in the
289call, not the class involved in the definition of foo().
290
291But notice this:
292
293 >>> class E(C):
294 ... def foo(cls, y): # override C.foo
295 ... print "E.foo() called"
296 ... C.foo(y)
297 ... foo = classmethod(foo)
298
299 >>> E.foo(1)
300 E.foo() called
Tim Peters90ba8d92001-09-09 01:21:31 +0000301 classmethod test.test_descrtut.C 1
Tim Peters95c99e52001-09-03 01:24:30 +0000302 >>> e = E()
303 >>> e.foo(1)
304 E.foo() called
Tim Peters90ba8d92001-09-09 01:21:31 +0000305 classmethod test.test_descrtut.C 1
Tim Peters95c99e52001-09-03 01:24:30 +0000306
307In this example, the call to C.foo() from E.foo() will see class C as its
308first argument, not class E. This is to be expected, since the call
309specifies the class C. But it stresses the difference between these class
310methods and methods defined in metaclasses (where an upcall to a metamethod
311would pass the target class as an explicit first argument).
312"""
313
314test_5 = """
315
316Attributes defined by get/set methods
317
318
Guido van Rossum8bce4ac2001-09-06 21:56:42 +0000319 >>> class property(object):
Tim Peters95c99e52001-09-03 01:24:30 +0000320 ...
321 ... def __init__(self, get, set=None):
322 ... self.__get = get
323 ... self.__set = set
324 ...
325 ... def __get__(self, inst, type=None):
326 ... return self.__get(inst)
327 ...
328 ... def __set__(self, inst, value):
329 ... if self.__set is None:
330 ... raise AttributeError, "this attribute is read-only"
331 ... return self.__set(inst, value)
332
333Now let's define a class with an attribute x defined by a pair of methods,
334getx() and and setx():
335
336 >>> class C(object):
337 ...
338 ... def __init__(self):
339 ... self.__x = 0
340 ...
341 ... def getx(self):
342 ... return self.__x
343 ...
344 ... def setx(self, x):
345 ... if x < 0: x = 0
346 ... self.__x = x
347 ...
Guido van Rossum8bce4ac2001-09-06 21:56:42 +0000348 ... x = property(getx, setx)
Tim Peters95c99e52001-09-03 01:24:30 +0000349
350Here's a small demonstration:
351
352 >>> a = C()
353 >>> a.x = 10
354 >>> print a.x
355 10
356 >>> a.x = -10
357 >>> print a.x
358 0
359 >>>
360
Guido van Rossum8bce4ac2001-09-06 21:56:42 +0000361Hmm -- property is builtin now, so let's try it that way too.
Tim Peters95c99e52001-09-03 01:24:30 +0000362
Guido van Rossum8bce4ac2001-09-06 21:56:42 +0000363 >>> del property # unmask the builtin
364 >>> property
365 <type 'property'>
Tim Peters95c99e52001-09-03 01:24:30 +0000366
367 >>> class C(object):
368 ... def __init__(self):
369 ... self.__x = 0
370 ... def getx(self):
371 ... return self.__x
372 ... def setx(self, x):
373 ... if x < 0: x = 0
374 ... self.__x = x
Guido van Rossum8bce4ac2001-09-06 21:56:42 +0000375 ... x = property(getx, setx)
Tim Peters95c99e52001-09-03 01:24:30 +0000376
377
378 >>> a = C()
379 >>> a.x = 10
380 >>> print a.x
381 10
382 >>> a.x = -10
383 >>> print a.x
384 0
385 >>>
386"""
387
388test_6 = """
389
390Method resolution order
391
392This example is implicit in the writeup.
393
394>>> class A: # classic class
395... def save(self):
396... print "called A.save()"
397>>> class B(A):
398... pass
399>>> class C(A):
400... def save(self):
401... print "called C.save()"
402>>> class D(B, C):
403... pass
404
405>>> D().save()
406called A.save()
407
408>>> class A(object): # new class
409... def save(self):
410... print "called A.save()"
411>>> class B(A):
412... pass
413>>> class C(A):
414... def save(self):
415... print "called C.save()"
416>>> class D(B, C):
417... pass
418
419>>> D().save()
420called C.save()
421"""
422
423class A(object):
424 def m(self):
425 return "A"
426
427class B(A):
428 def m(self):
429 return "B" + super(B, self).m()
430
431class C(A):
432 def m(self):
433 return "C" + super(C, self).m()
434
435class D(C, B):
436 def m(self):
437 return "D" + super(D, self).m()
438
439
440test_7 = """
441
442Cooperative methods and "super"
443
444>>> print D().m() # "DCBA"
445DCBA
446"""
447
448test_8 = """
449
450Backwards incompatibilities
451
452>>> class A:
453... def foo(self):
454... print "called A.foo()"
455
456>>> class B(A):
457... pass
458
459>>> class C(A):
460... def foo(self):
461... B.foo(self)
462
463>>> C().foo()
464Traceback (most recent call last):
465 ...
466TypeError: unbound method foo() must be called with B instance as first argument (got C instance instead)
467
468>>> class C(A):
469... def foo(self):
470... A.foo(self)
471>>> C().foo()
472called A.foo()
473"""
474
475__test__ = {"tut1": test_1,
476 "tut2": test_2,
477 "tut3": test_3,
478 "tut4": test_4,
479 "tut5": test_5,
480 "tut6": test_6,
481 "tut7": test_7,
482 "tut8": test_8}
483
484# Magic test name that regrtest.py invokes *after* importing this module.
485# This worms around a bootstrap problem.
486# Note that doctest and regrtest both look in sys.argv for a "-v" argument,
487# so this works as expected in both ways of running regrtest.
Tim Petersa0a62222001-09-09 06:12:01 +0000488def test_main(verbose=None):
489 # Obscure: import this module as test.test_descrtut instead of as
490 # plain test_descrtut because the name of this module works its way
491 # into the doctest examples, and unless the full test.test_descrtut
492 # business is used the name can change depending on how the test is
493 # invoked.
494 import test_support, test.test_descrtut
495 test_support.run_doctest(test.test_descrtut, verbose)
Tim Peters95c99e52001-09-03 01:24:30 +0000496
497# This part isn't needed for regrtest, but for running the test directly.
498if __name__ == "__main__":
Tim Petersa0a62222001-09-09 06:12:01 +0000499 test_main(1)