blob: b84d6447850a069435e508f2177826449375a342 [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
Benjamin Petersonee8712c2008-05-20 21:35:26 +000011from test.support import sortdict
Tim Peters95c99e52001-09-03 01:24:30 +000012import pprint
13
Tim Petersa427a2b2001-10-29 22:25:45 +000014class defaultdict(dict):
Tim Peters95c99e52001-09-03 01:24:30 +000015 def __init__(self, default=None):
Tim Petersa427a2b2001-10-29 22:25:45 +000016 dict.__init__(self)
Tim Peters95c99e52001-09-03 01:24:30 +000017 self.default = default
18
19 def __getitem__(self, key):
20 try:
Tim Petersa427a2b2001-10-29 22:25:45 +000021 return dict.__getitem__(self, key)
Tim Peters95c99e52001-09-03 01:24:30 +000022 except KeyError:
23 return self.default
24
25 def get(self, key, *args):
26 if not args:
27 args = (self.default,)
Tim Petersa427a2b2001-10-29 22:25:45 +000028 return dict.get(self, key, *args)
Tim Peters95c99e52001-09-03 01:24:30 +000029
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
Georg Brandl88fc6642007-02-09 21:28:07 +000039 >>> print(defaultdict) # show our type
Benjamin Petersonab078e92016-07-13 21:13:29 -070040 <class 'test.test_descrtut.defaultdict'>
Georg Brandl88fc6642007-02-09 21:28:07 +000041 >>> print(type(defaultdict)) # its metatype
Benjamin Petersonab078e92016-07-13 21:13:29 -070042 <class 'type'>
Tim Peters95c99e52001-09-03 01:24:30 +000043 >>> a = defaultdict(default=0.0) # create an instance
Georg Brandl88fc6642007-02-09 21:28:07 +000044 >>> print(a) # show the instance
Tim Peters95c99e52001-09-03 01:24:30 +000045 {}
Georg Brandl88fc6642007-02-09 21:28:07 +000046 >>> print(type(a)) # show its type
Benjamin Petersonab078e92016-07-13 21:13:29 -070047 <class 'test.test_descrtut.defaultdict'>
Georg Brandl88fc6642007-02-09 21:28:07 +000048 >>> print(a.__class__) # show its class
Benjamin Petersonab078e92016-07-13 21:13:29 -070049 <class 'test.test_descrtut.defaultdict'>
Georg Brandl88fc6642007-02-09 21:28:07 +000050 >>> print(type(a) is a.__class__) # its type is its class
Guido van Rossum77f6a652002-04-03 22:41:51 +000051 True
Tim Peters95c99e52001-09-03 01:24:30 +000052 >>> a[1] = 3.25 # modify the instance
Georg Brandl88fc6642007-02-09 21:28:07 +000053 >>> print(a) # show the new value
Tim Peters95c99e52001-09-03 01:24:30 +000054 {1: 3.25}
Georg Brandl88fc6642007-02-09 21:28:07 +000055 >>> print(a[1]) # show the new item
Tim Peters95c99e52001-09-03 01:24:30 +000056 3.25
Mark Dickinson934896d2009-02-21 20:59:32 +000057 >>> print(a[0]) # a non-existent item
Tim Peters95c99e52001-09-03 01:24:30 +000058 0.0
Tim Petersa427a2b2001-10-29 22:25:45 +000059 >>> a.merge({1:100, 2:200}) # use a dict method
Georg Brandl88fc6642007-02-09 21:28:07 +000060 >>> print(sortdict(a)) # show the result
Tim Peters95c99e52001-09-03 01:24:30 +000061 {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
Guido van Rossum7131f842007-02-09 20:13:25 +000068 >>> print(sorted(a.keys()))
Tim Peters95c99e52001-09-03 01:24:30 +000069 [1, 2]
Georg Brandl88fc6642007-02-09 21:28:07 +000070 >>> a['print'] = print # need the print function here
71 >>> exec("x = 3; print(x)", a)
Tim Peters95c99e52001-09-03 01:24:30 +000072 3
Guido van Rossum7131f842007-02-09 20:13:25 +000073 >>> print(sorted(a.keys(), key=lambda x: (str(type(x)), x)))
Georg Brandl88fc6642007-02-09 21:28:07 +000074 [1, 2, '__builtins__', 'print', 'x']
Guido van Rossum7131f842007-02-09 20:13:25 +000075 >>> print(a['x'])
Tim Peters95c99e52001-09-03 01:24:30 +000076 3
77 >>>
78
Tim Peters95c99e52001-09-03 01:24:30 +000079Now I'll show that defaultdict instances have dynamic instance variables,
80just like classic classes:
81
82 >>> a.default = -1
Guido van Rossum7131f842007-02-09 20:13:25 +000083 >>> print(a["noway"])
Tim Peters95c99e52001-09-03 01:24:30 +000084 -1
85 >>> a.default = -1000
Guido van Rossum7131f842007-02-09 20:13:25 +000086 >>> print(a["noway"])
Tim Peters95c99e52001-09-03 01:24:30 +000087 -1000
Tim Peters5d2b77c2001-09-03 05:47:38 +000088 >>> 'default' in dir(a)
Guido van Rossum77f6a652002-04-03 22:41:51 +000089 True
Tim Peters95c99e52001-09-03 01:24:30 +000090 >>> a.x1 = 100
91 >>> a.x2 = 200
Guido van Rossum7131f842007-02-09 20:13:25 +000092 >>> print(a.x1)
Tim Peters95c99e52001-09-03 01:24:30 +000093 100
Tim Peters5d2b77c2001-09-03 05:47:38 +000094 >>> d = dir(a)
95 >>> 'default' in d and 'x1' in d and 'x2' in d
Guido van Rossum77f6a652002-04-03 22:41:51 +000096 True
Guido van Rossum7131f842007-02-09 20:13:25 +000097 >>> print(sortdict(a.__dict__))
Tim Peterse2052ab2003-02-18 16:54:41 +000098 {'default': -1000, 'x1': 100, 'x2': 200}
Tim Peters95c99e52001-09-03 01:24:30 +000099 >>>
100"""
101
Tim Petersa427a2b2001-10-29 22:25:45 +0000102class defaultdict2(dict):
Tim Peters95c99e52001-09-03 01:24:30 +0000103 __slots__ = ['default']
104
105 def __init__(self, default=None):
Tim Petersa427a2b2001-10-29 22:25:45 +0000106 dict.__init__(self)
Tim Peters95c99e52001-09-03 01:24:30 +0000107 self.default = default
108
109 def __getitem__(self, key):
110 try:
Tim Petersa427a2b2001-10-29 22:25:45 +0000111 return dict.__getitem__(self, key)
Tim Peters95c99e52001-09-03 01:24:30 +0000112 except KeyError:
113 return self.default
114
115 def get(self, key, *args):
116 if not args:
117 args = (self.default,)
Tim Petersa427a2b2001-10-29 22:25:45 +0000118 return dict.get(self, key, *args)
Tim Peters95c99e52001-09-03 01:24:30 +0000119
120 def merge(self, other):
121 for key in other:
122 if key not in self:
123 self[key] = other[key]
124
125test_2 = """
126
127The __slots__ declaration takes a list of instance variables, and reserves
128space for exactly these in the instance. When __slots__ is used, other
129instance variables cannot be assigned to:
130
131 >>> a = defaultdict2(default=0.0)
132 >>> a[1]
133 0.0
134 >>> a.default = -1
135 >>> a[1]
136 -1
137 >>> a.x1 = 1
138 Traceback (most recent call last):
139 File "<stdin>", line 1, in ?
140 AttributeError: 'defaultdict2' object has no attribute 'x1'
141 >>>
142
143"""
144
145test_3 = """
146
147Introspecting instances of built-in types
148
149For instance of built-in types, x.__class__ is now the same as type(x):
150
151 >>> type([])
Benjamin Petersonab078e92016-07-13 21:13:29 -0700152 <class 'list'>
Tim Peters95c99e52001-09-03 01:24:30 +0000153 >>> [].__class__
Benjamin Petersonab078e92016-07-13 21:13:29 -0700154 <class 'list'>
Tim Peters95c99e52001-09-03 01:24:30 +0000155 >>> list
Benjamin Petersonab078e92016-07-13 21:13:29 -0700156 <class 'list'>
Tim Peters95c99e52001-09-03 01:24:30 +0000157 >>> isinstance([], list)
Guido van Rossum77f6a652002-04-03 22:41:51 +0000158 True
Tim Petersa427a2b2001-10-29 22:25:45 +0000159 >>> isinstance([], dict)
Guido van Rossum77f6a652002-04-03 22:41:51 +0000160 False
Tim Peters95c99e52001-09-03 01:24:30 +0000161 >>> isinstance([], object)
Guido van Rossum77f6a652002-04-03 22:41:51 +0000162 True
Tim Peters95c99e52001-09-03 01:24:30 +0000163 >>>
164
Neal Norwitz8dfc4a92007-08-11 06:39:53 +0000165You can get the information from the list type:
Tim Peters95c99e52001-09-03 01:24:30 +0000166
167 >>> pprint.pprint(dir(list)) # like list.__dict__.keys(), but sorted
168 ['__add__',
169 '__class__',
170 '__contains__',
171 '__delattr__',
172 '__delitem__',
Benjamin Peterson82b00c12011-05-24 11:09:06 -0500173 '__dir__',
Tim Peters80440552002-02-19 04:25:19 +0000174 '__doc__',
Tim Peters95c99e52001-09-03 01:24:30 +0000175 '__eq__',
Eric Smith8c663262007-08-25 02:26:07 +0000176 '__format__',
Tim Peters95c99e52001-09-03 01:24:30 +0000177 '__ge__',
Guido van Rossum867a8d22001-09-21 19:29:08 +0000178 '__getattribute__',
Tim Peters95c99e52001-09-03 01:24:30 +0000179 '__getitem__',
Tim Peters95c99e52001-09-03 01:24:30 +0000180 '__gt__',
181 '__hash__',
182 '__iadd__',
183 '__imul__',
184 '__init__',
Nick Coghland78448e2016-07-30 16:26:03 +1000185 '__init_subclass__',
Raymond Hettinger14bd6de2002-05-31 21:40:38 +0000186 '__iter__',
Tim Peters95c99e52001-09-03 01:24:30 +0000187 '__le__',
188 '__len__',
189 '__lt__',
190 '__mul__',
191 '__ne__',
192 '__new__',
Guido van Rossum3926a632001-09-25 16:25:58 +0000193 '__reduce__',
Guido van Rossumc53f0092003-02-18 22:05:12 +0000194 '__reduce_ex__',
Tim Peters95c99e52001-09-03 01:24:30 +0000195 '__repr__',
Raymond Hettingeraf28e4b2003-11-08 12:39:53 +0000196 '__reversed__',
Tim Peters95c99e52001-09-03 01:24:30 +0000197 '__rmul__',
198 '__setattr__',
199 '__setitem__',
Martin v. Löwis00709aa2008-06-04 14:18:43 +0000200 '__sizeof__',
Tim Peters95c99e52001-09-03 01:24:30 +0000201 '__str__',
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000202 '__subclasshook__',
Tim Peters95c99e52001-09-03 01:24:30 +0000203 'append',
Eli Benderskycbbaa962011-02-25 05:47:53 +0000204 'clear',
205 'copy',
Tim Peters95c99e52001-09-03 01:24:30 +0000206 'count',
207 'extend',
208 'index',
209 'insert',
210 'pop',
211 'remove',
212 'reverse',
Raymond Hettinger64958a12003-12-17 20:43:33 +0000213 'sort']
Tim Peters95c99e52001-09-03 01:24:30 +0000214
215The new introspection API gives more information than the old one: in
216addition to the regular methods, it also shows the methods that are
217normally invoked through special notations, e.g. __iadd__ (+=), __len__
218(len), __ne__ (!=). You can invoke any method from this list directly:
219
220 >>> a = ['tic', 'tac']
221 >>> list.__len__(a) # same as len(a)
222 2
223 >>> a.__len__() # ditto
224 2
225 >>> list.append(a, 'toe') # same as a.append('toe')
226 >>> a
227 ['tic', 'tac', 'toe']
228 >>>
229
230This is just like it is for user-defined classes.
231"""
232
233test_4 = """
234
235Static methods and class methods
236
237The new introspection API makes it possible to add static methods and class
238methods. Static methods are easy to describe: they behave pretty much like
239static methods in C++ or Java. Here's an example:
240
241 >>> class C:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000242 ...
Guido van Rossum5a8a0372005-01-16 00:25:31 +0000243 ... @staticmethod
Tim Peters95c99e52001-09-03 01:24:30 +0000244 ... def foo(x, y):
Guido van Rossum7131f842007-02-09 20:13:25 +0000245 ... print("staticmethod", x, y)
Tim Peters95c99e52001-09-03 01:24:30 +0000246
247 >>> C.foo(1, 2)
248 staticmethod 1 2
249 >>> c = C()
250 >>> c.foo(1, 2)
251 staticmethod 1 2
252
253Class methods use a similar pattern to declare methods that receive an
254implicit first argument that is the *class* for which they are invoked.
255
256 >>> class C:
Guido van Rossum5a8a0372005-01-16 00:25:31 +0000257 ... @classmethod
Tim Peters95c99e52001-09-03 01:24:30 +0000258 ... def foo(cls, y):
Guido van Rossum7131f842007-02-09 20:13:25 +0000259 ... print("classmethod", cls, y)
Tim Peters95c99e52001-09-03 01:24:30 +0000260
261 >>> C.foo(1)
Benjamin Petersonab078e92016-07-13 21:13:29 -0700262 classmethod <class 'test.test_descrtut.C'> 1
Tim Peters95c99e52001-09-03 01:24:30 +0000263 >>> c = C()
264 >>> c.foo(1)
Benjamin Petersonab078e92016-07-13 21:13:29 -0700265 classmethod <class 'test.test_descrtut.C'> 1
Tim Peters95c99e52001-09-03 01:24:30 +0000266
267 >>> class D(C):
268 ... pass
269
270 >>> D.foo(1)
Benjamin Petersonab078e92016-07-13 21:13:29 -0700271 classmethod <class 'test.test_descrtut.D'> 1
Tim Peters95c99e52001-09-03 01:24:30 +0000272 >>> d = D()
273 >>> d.foo(1)
Benjamin Petersonab078e92016-07-13 21:13:29 -0700274 classmethod <class 'test.test_descrtut.D'> 1
Tim Peters95c99e52001-09-03 01:24:30 +0000275
276This prints "classmethod __main__.D 1" both times; in other words, the
277class passed as the first argument of foo() is the class involved in the
278call, not the class involved in the definition of foo().
279
280But notice this:
281
282 >>> class E(C):
Guido van Rossum5a8a0372005-01-16 00:25:31 +0000283 ... @classmethod
Tim Peters95c99e52001-09-03 01:24:30 +0000284 ... def foo(cls, y): # override C.foo
Guido van Rossum7131f842007-02-09 20:13:25 +0000285 ... print("E.foo() called")
Tim Peters95c99e52001-09-03 01:24:30 +0000286 ... C.foo(y)
Tim Peters95c99e52001-09-03 01:24:30 +0000287
288 >>> E.foo(1)
289 E.foo() called
Benjamin Petersonab078e92016-07-13 21:13:29 -0700290 classmethod <class 'test.test_descrtut.C'> 1
Tim Peters95c99e52001-09-03 01:24:30 +0000291 >>> e = E()
292 >>> e.foo(1)
293 E.foo() called
Benjamin Petersonab078e92016-07-13 21:13:29 -0700294 classmethod <class 'test.test_descrtut.C'> 1
Tim Peters95c99e52001-09-03 01:24:30 +0000295
296In this example, the call to C.foo() from E.foo() will see class C as its
297first argument, not class E. This is to be expected, since the call
298specifies the class C. But it stresses the difference between these class
299methods and methods defined in metaclasses (where an upcall to a metamethod
300would pass the target class as an explicit first argument).
301"""
302
303test_5 = """
304
305Attributes defined by get/set methods
306
307
Guido van Rossum8bce4ac2001-09-06 21:56:42 +0000308 >>> class property(object):
Tim Peters95c99e52001-09-03 01:24:30 +0000309 ...
310 ... def __init__(self, get, set=None):
311 ... self.__get = get
312 ... self.__set = set
313 ...
314 ... def __get__(self, inst, type=None):
315 ... return self.__get(inst)
316 ...
317 ... def __set__(self, inst, value):
318 ... if self.__set is None:
Collin Winter3add4d72007-08-29 23:37:32 +0000319 ... raise AttributeError("this attribute is read-only")
Tim Peters95c99e52001-09-03 01:24:30 +0000320 ... return self.__set(inst, value)
321
322Now let's define a class with an attribute x defined by a pair of methods,
Terry Jan Reedyc30b7b12013-03-11 17:57:08 -0400323getx() and setx():
Tim Peters95c99e52001-09-03 01:24:30 +0000324
325 >>> class C(object):
326 ...
327 ... def __init__(self):
328 ... self.__x = 0
329 ...
330 ... def getx(self):
331 ... return self.__x
332 ...
333 ... def setx(self, x):
334 ... if x < 0: x = 0
335 ... self.__x = x
336 ...
Guido van Rossum8bce4ac2001-09-06 21:56:42 +0000337 ... x = property(getx, setx)
Tim Peters95c99e52001-09-03 01:24:30 +0000338
339Here's a small demonstration:
340
341 >>> a = C()
342 >>> a.x = 10
Guido van Rossum7131f842007-02-09 20:13:25 +0000343 >>> print(a.x)
Tim Peters95c99e52001-09-03 01:24:30 +0000344 10
345 >>> a.x = -10
Guido van Rossum7131f842007-02-09 20:13:25 +0000346 >>> print(a.x)
Tim Peters95c99e52001-09-03 01:24:30 +0000347 0
348 >>>
349
Guido van Rossum8bce4ac2001-09-06 21:56:42 +0000350Hmm -- property is builtin now, so let's try it that way too.
Tim Peters95c99e52001-09-03 01:24:30 +0000351
Guido van Rossum8bce4ac2001-09-06 21:56:42 +0000352 >>> del property # unmask the builtin
353 >>> property
Benjamin Petersonab078e92016-07-13 21:13:29 -0700354 <class 'property'>
Tim Peters95c99e52001-09-03 01:24:30 +0000355
356 >>> class C(object):
357 ... def __init__(self):
358 ... self.__x = 0
359 ... def getx(self):
360 ... return self.__x
361 ... def setx(self, x):
362 ... if x < 0: x = 0
363 ... self.__x = x
Guido van Rossum8bce4ac2001-09-06 21:56:42 +0000364 ... x = property(getx, setx)
Tim Peters95c99e52001-09-03 01:24:30 +0000365
366
367 >>> a = C()
368 >>> a.x = 10
Guido van Rossum7131f842007-02-09 20:13:25 +0000369 >>> print(a.x)
Tim Peters95c99e52001-09-03 01:24:30 +0000370 10
371 >>> a.x = -10
Guido van Rossum7131f842007-02-09 20:13:25 +0000372 >>> print(a.x)
Tim Peters95c99e52001-09-03 01:24:30 +0000373 0
374 >>>
375"""
376
377test_6 = """
378
379Method resolution order
380
381This example is implicit in the writeup.
382
Thomas Wouters28bc7682006-04-15 09:03:16 +0000383>>> class A: # implicit new-style class
Tim Peters95c99e52001-09-03 01:24:30 +0000384... def save(self):
Guido van Rossum7131f842007-02-09 20:13:25 +0000385... print("called A.save()")
Tim Peters95c99e52001-09-03 01:24:30 +0000386>>> class B(A):
387... pass
388>>> class C(A):
389... def save(self):
Guido van Rossum7131f842007-02-09 20:13:25 +0000390... print("called C.save()")
Tim Peters95c99e52001-09-03 01:24:30 +0000391>>> class D(B, C):
392... pass
393
394>>> D().save()
Thomas Wouters28bc7682006-04-15 09:03:16 +0000395called C.save()
Tim Peters95c99e52001-09-03 01:24:30 +0000396
Thomas Wouters28bc7682006-04-15 09:03:16 +0000397>>> class A(object): # explicit new-style class
Tim Peters95c99e52001-09-03 01:24:30 +0000398... def save(self):
Guido van Rossum7131f842007-02-09 20:13:25 +0000399... print("called A.save()")
Tim Peters95c99e52001-09-03 01:24:30 +0000400>>> class B(A):
401... pass
402>>> class C(A):
403... def save(self):
Guido van Rossum7131f842007-02-09 20:13:25 +0000404... print("called C.save()")
Tim Peters95c99e52001-09-03 01:24:30 +0000405>>> class D(B, C):
406... pass
407
408>>> D().save()
409called C.save()
410"""
411
412class A(object):
413 def m(self):
414 return "A"
415
416class B(A):
417 def m(self):
418 return "B" + super(B, self).m()
419
420class C(A):
421 def m(self):
422 return "C" + super(C, self).m()
423
424class D(C, B):
425 def m(self):
426 return "D" + super(D, self).m()
427
428
429test_7 = """
430
431Cooperative methods and "super"
432
Guido van Rossum7131f842007-02-09 20:13:25 +0000433>>> print(D().m()) # "DCBA"
Tim Peters95c99e52001-09-03 01:24:30 +0000434DCBA
435"""
436
437test_8 = """
438
439Backwards incompatibilities
440
441>>> class A:
442... def foo(self):
Guido van Rossum7131f842007-02-09 20:13:25 +0000443... print("called A.foo()")
Tim Peters95c99e52001-09-03 01:24:30 +0000444
445>>> class B(A):
446... pass
447
448>>> class C(A):
449... def foo(self):
450... B.foo(self)
451
452>>> C().foo()
Christian Heimes4a22b5d2007-11-25 09:39:14 +0000453called A.foo()
Tim Peters95c99e52001-09-03 01:24:30 +0000454
455>>> class C(A):
456... def foo(self):
457... A.foo(self)
458>>> C().foo()
459called A.foo()
460"""
461
462__test__ = {"tut1": test_1,
463 "tut2": test_2,
464 "tut3": test_3,
465 "tut4": test_4,
466 "tut5": test_5,
467 "tut6": test_6,
468 "tut7": test_7,
469 "tut8": test_8}
470
471# Magic test name that regrtest.py invokes *after* importing this module.
472# This worms around a bootstrap problem.
473# Note that doctest and regrtest both look in sys.argv for a "-v" argument,
474# so this works as expected in both ways of running regrtest.
Tim Petersa0a62222001-09-09 06:12:01 +0000475def test_main(verbose=None):
476 # Obscure: import this module as test.test_descrtut instead of as
477 # plain test_descrtut because the name of this module works its way
478 # into the doctest examples, and unless the full test.test_descrtut
479 # business is used the name can change depending on how the test is
480 # invoked.
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000481 from test import support, test_descrtut
Benjamin Petersonab078e92016-07-13 21:13:29 -0700482 support.run_doctest(test_descrtut, verbose)
Tim Peters95c99e52001-09-03 01:24:30 +0000483
484# This part isn't needed for regrtest, but for running the test directly.
485if __name__ == "__main__":
Tim Petersa0a62222001-09-09 06:12:01 +0000486 test_main(1)