Debian Codegraph @

lib-python/3/test/test_descrtut.py

raw symbols SCIP
1 # This contains most of the executable examples from Guido's descr
2 # tutorial, once at
3 #
4 # https://www.python.org/download/releases/2.2.3/descrintro/
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
11 from test.support import sortdict
12 import pprint
13 import doctest
14 import unittest
15
16
17 class defaultdict(dict):
18 def __init__(self, default=None):
19 dict.__init__(self)
20 self.default = default
21
22 def __getitem__(self, key):
23 try:
24 return dict.__getitem__(self, key)
25 except KeyError:
26 return self.default
27
28 def get(self, key, *args):
29 if not args:
30 args = (self.default,)
31 return dict.get(self, key, *args)
32
33 def merge(self, other):
34 for key in other:
35 if key not in self:
36 self[key] = other[key]
37
38 test_1 = """
39
40 Here's the new type at work:
41
42 >>> print(defaultdict) # show our type
43 <class '%(modname)s.defaultdict'>
44 >>> print(type(defaultdict)) # its metatype
45 <class 'type'>
46 >>> a = defaultdict(default=0.0) # create an instance
47 >>> print(a) # show the instance
48 {}
49 >>> print(type(a)) # show its type
50 <class '%(modname)s.defaultdict'>
51 >>> print(a.__class__) # show its class
52 <class '%(modname)s.defaultdict'>
53 >>> print(type(a) is a.__class__) # its type is its class
54 True
55 >>> a[1] = 3.25 # modify the instance
56 >>> print(a) # show the new value
57 {1: 3.25}
58 >>> print(a[1]) # show the new item
59 3.25
60 >>> print(a[0]) # a non-existent item
61 0.0
62 >>> a.merge({1:100, 2:200}) # use a dict method
63 >>> print(sortdict(a)) # show the result
64 {1: 3.25, 2: 200}
65 >>>
66
67 We can also use the new type in contexts where classic only allows "real"
68 dictionaries, such as the locals/globals dictionaries for the exec
69 statement or the built-in function eval():
70
71 >>> print(sorted(a.keys()))
72 [1, 2]
73 >>> a['print'] = print # need the print function here
74 >>> exec("x = 3; print(x)", a)
75 3
76 >>> print(sorted(a.keys(), key=lambda x: (str(type(x)), x)))
77 [1, 2, '__builtins__', 'print', 'x']
78 >>> print(a['x'])
79 3
80 >>>
81
82 Now I'll show that defaultdict instances have dynamic instance variables,
83 just like classic classes:
84
85 >>> a.default = -1
86 >>> print(a["noway"])
87 -1
88 >>> a.default = -1000
89 >>> print(a["noway"])
90 -1000
91 >>> 'default' in dir(a)
92 True
93 >>> a.x1 = 100
94 >>> a.x2 = 200
95 >>> print(a.x1)
96 100
97 >>> d = dir(a)
98 >>> 'default' in d and 'x1' in d and 'x2' in d
99 True
100 >>> print(sortdict(a.__dict__))
101 {'default': -1000, 'x1': 100, 'x2': 200}
102 >>>
103 """ % {'modname': __name__}
104
105 class defaultdict2(dict):
106 __slots__ = ['default']
107
108 def __init__(self, default=None):
109 dict.__init__(self)
110 self.default = default
111
112 def __getitem__(self, key):
113 try:
114 return dict.__getitem__(self, key)
115 except KeyError:
116 return self.default
117
118 def get(self, key, *args):
119 if not args:
120 args = (self.default,)
121 return dict.get(self, key, *args)
122
123 def merge(self, other):
124 for key in other:
125 if key not in self:
126 self[key] = other[key]
127
128 test_2 = """
129
130 The __slots__ declaration takes a list of instance variables, and reserves
131 space for exactly these in the instance. When __slots__ is used, other
132 instance variables cannot be assigned to:
133
134 >>> a = defaultdict2(default=0.0)
135 >>> a[1]
136 0.0
137 >>> a.default = -1
138 >>> a[1]
139 -1
140 >>> a.x1 = 1
141 Traceback (most recent call last):
142 File "<stdin>", line 1, in ?
143 AttributeError: 'defaultdict2' object has no attribute 'x1'
144 >>>
145
146 """
147
148 test_3 = """
149
150 Introspecting instances of built-in types
151
152 For instance of built-in types, x.__class__ is now the same as type(x):
153
154 >>> type([])
155 <class 'list'>
156 >>> [].__class__
157 <class 'list'>
158 >>> list
159 <class 'list'>
160 >>> isinstance([], list)
161 True
162 >>> isinstance([], dict)
163 False
164 >>> isinstance([], object)
165 True
166 >>>
167
168 You can get the information from the list type:
169
170 >>> pprint.pprint(dir(list)) # like list.__dict__.keys(), but sorted
171 ['__add__',
172 '__class__',
173 '__class_getitem__',
174 '__contains__',
175 '__delattr__',
176 '__delitem__',
177 '__dir__',
178 '__doc__',
179 '__eq__',
180 '__format__',
181 '__ge__',
182 '__getattribute__',
183 '__getitem__',
184 '__getstate__',
185 '__gt__',
186 '__hash__',
187 '__iadd__',
188 '__imul__',
189 '__init__',
190 '__init_subclass__',
191 '__iter__',
192 '__le__',
193 '__len__',
194 '__lt__',
195 '__mul__',
196 '__ne__',
197 '__new__',
198 '__reduce__',
199 '__reduce_ex__',
200 '__repr__',
201 '__reversed__',
202 '__rmul__',
203 '__setattr__',
204 '__setitem__',
205 '__str__',
206 '__subclasshook__',
207 'append',
208 'clear',
209 'copy',
210 'count',
211 'extend',
212 'index',
213 'insert',
214 'pop',
215 'remove',
216 'reverse',
217 'sort']
218
219 The new introspection API gives more information than the old one: in
220 addition to the regular methods, it also shows the methods that are
221 normally invoked through special notations, e.g. __iadd__ (+=), __len__
222 (len), __ne__ (!=). You can invoke any method from this list directly:
223
224 >>> a = ['tic', 'tac']
225 >>> list.__len__(a) # same as len(a)
226 2
227 >>> a.__len__() # ditto
228 2
229 >>> list.append(a, 'toe') # same as a.append('toe')
230 >>> a
231 ['tic', 'tac', 'toe']
232 >>>
233
234 This is just like it is for user-defined classes.
235 """
236
237 test_4 = """
238
239 Static methods and class methods
240
241 The new introspection API makes it possible to add static methods and class
242 methods. Static methods are easy to describe: they behave pretty much like
243 static methods in C++ or Java. Here's an example:
244
245 >>> class C:
246 ...
247 ... @staticmethod
248 ... def foo(x, y):
249 ... print("staticmethod", x, y)
250
251 >>> C.foo(1, 2)
252 staticmethod 1 2
253 >>> c = C()
254 >>> c.foo(1, 2)
255 staticmethod 1 2
256
257 Class methods use a similar pattern to declare methods that receive an
258 implicit first argument that is the *class* for which they are invoked.
259
260 >>> class C:
261 ... @classmethod
262 ... def foo(cls, y):
263 ... print("classmethod", cls, y)
264
265 >>> C.foo(1)
266 classmethod <class '%(modname)s.C'> 1
267 >>> c = C()
268 >>> c.foo(1)
269 classmethod <class '%(modname)s.C'> 1
270
271 >>> class D(C):
272 ... pass
273
274 >>> D.foo(1)
275 classmethod <class '%(modname)s.D'> 1
276 >>> d = D()
277 >>> d.foo(1)
278 classmethod <class '%(modname)s.D'> 1
279
280 This prints "classmethod __main__.D 1" both times; in other words, the
281 class passed as the first argument of foo() is the class involved in the
282 call, not the class involved in the definition of foo().
283
284 But notice this:
285
286 >>> class E(C):
287 ... @classmethod
288 ... def foo(cls, y): # override C.foo
289 ... print("E.foo() called")
290 ... C.foo(y)
291
292 >>> E.foo(1)
293 E.foo() called
294 classmethod <class '%(modname)s.C'> 1
295 >>> e = E()
296 >>> e.foo(1)
297 E.foo() called
298 classmethod <class '%(modname)s.C'> 1
299
300 In this example, the call to C.foo() from E.foo() will see class C as its
301 first argument, not class E. This is to be expected, since the call
302 specifies the class C. But it stresses the difference between these class
303 methods and methods defined in metaclasses (where an upcall to a metamethod
304 would pass the target class as an explicit first argument).
305 """ % {'modname': __name__}
306
307 test_5 = """
308
309 Attributes defined by get/set methods
310
311
312 >>> class property(object):
313 ...
314 ... def __init__(self, get, set=None):
315 ... self.__get = get
316 ... self.__set = set
317 ...
318 ... def __get__(self, inst, type=None):
319 ... return self.__get(inst)
320 ...
321 ... def __set__(self, inst, value):
322 ... if self.__set is None:
323 ... raise AttributeError("this attribute is read-only")
324 ... return self.__set(inst, value)
325
326 Now let's define a class with an attribute x defined by a pair of methods,
327 getx() and setx():
328
329 >>> class C(object):
330 ...
331 ... def __init__(self):
332 ... self.__x = 0
333 ...
334 ... def getx(self):
335 ... return self.__x
336 ...
337 ... def setx(self, x):
338 ... if x < 0: x = 0
339 ... self.__x = x
340 ...
341 ... x = property(getx, setx)
342
343 Here's a small demonstration:
344
345 >>> a = C()
346 >>> a.x = 10
347 >>> print(a.x)
348 10
349 >>> a.x = -10
350 >>> print(a.x)
351 0
352 >>>
353
354 Hmm -- property is builtin now, so let's try it that way too.
355
356 >>> del property # unmask the builtin
357 >>> property
358 <class 'property'>
359
360 >>> class C(object):
361 ... def __init__(self):
362 ... self.__x = 0
363 ... def getx(self):
364 ... return self.__x
365 ... def setx(self, x):
366 ... if x < 0: x = 0
367 ... self.__x = x
368 ... x = property(getx, setx)
369
370
371 >>> a = C()
372 >>> a.x = 10
373 >>> print(a.x)
374 10
375 >>> a.x = -10
376 >>> print(a.x)
377 0
378 >>>
379 """
380
381 test_6 = """
382
383 Method resolution order
384
385 This example is implicit in the writeup.
386
387 >>> class A: # implicit new-style class
388 ... def save(self):
389 ... print("called A.save()")
390 >>> class B(A):
391 ... pass
392 >>> class C(A):
393 ... def save(self):
394 ... print("called C.save()")
395 >>> class D(B, C):
396 ... pass
397
398 >>> D().save()
399 called C.save()
400
401 >>> class A(object): # explicit new-style class
402 ... def save(self):
403 ... print("called A.save()")
404 >>> class B(A):
405 ... pass
406 >>> class C(A):
407 ... def save(self):
408 ... print("called C.save()")
409 >>> class D(B, C):
410 ... pass
411
412 >>> D().save()
413 called C.save()
414 """
415
416 class A(object):
417 def m(self):
418 return "A"
419
420 class B(A):
421 def m(self):
422 return "B" + super(B, self).m()
423
424 class C(A):
425 def m(self):
426 return "C" + super(C, self).m()
427
428 class D(C, B):
429 def m(self):
430 return "D" + super(D, self).m()
431
432
433 test_7 = """
434
435 Cooperative methods and "super"
436
437 >>> print(D().m()) # "DCBA"
438 DCBA
439 """
440
441 test_8 = """
442
443 Backwards incompatibilities
444
445 >>> class A:
446 ... def foo(self):
447 ... print("called A.foo()")
448
449 >>> class B(A):
450 ... pass
451
452 >>> class C(A):
453 ... def foo(self):
454 ... B.foo(self)
455
456 >>> C().foo()
457 called A.foo()
458
459 >>> class C(A):
460 ... def foo(self):
461 ... A.foo(self)
462 >>> C().foo()
463 called A.foo()
464 """
465
466 __test__ = {"tut1": test_1,
467 "tut2": test_2,
468 "tut3": test_3,
469 "tut4": test_4,
470 "tut5": test_5,
471 "tut6": test_6,
472 "tut7": test_7,
473 "tut8": test_8}
474
475 def load_tests(loader, tests, pattern):
476 tests.addTest(doctest.DocTestSuite())
477 return tests
478
479
480 if __name__ == "__main__":
481 unittest.main()