blob: 5b11666184336cfbc4c055906da8cc07bc2afd67 [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
Barry Warsaw04f357c2002-07-23 19:04:11 +000011from test.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
Guido van Rossuma4cb7882001-09-25 03:56:29 +000040 <class 'test.test_descrtut.defaultdict'>
Georg Brandl88fc6642007-02-09 21:28:07 +000041 >>> print(type(defaultdict)) # its metatype
Tim Peters95c99e52001-09-03 01:24:30 +000042 <type 'type'>
43 >>> 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
Guido van Rossuma4cb7882001-09-25 03:56:29 +000047 <class 'test.test_descrtut.defaultdict'>
Georg Brandl88fc6642007-02-09 21:28:07 +000048 >>> print(a.__class__) # show its class
Guido van Rossuma4cb7882001-09-25 03:56:29 +000049 <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
Georg Brandl88fc6642007-02-09 21:28:07 +000057 >>> print(a[0]) # a non-existant 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([])
152 <type 'list'>
153 >>> [].__class__
154 <type 'list'>
155 >>> list
156 <type 'list'>
157 >>> 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
165Under the new proposal, the __methods__ attribute no longer exists:
166
167 >>> [].__methods__
168 Traceback (most recent call last):
169 File "<stdin>", line 1, in ?
170 AttributeError: 'list' object has no attribute '__methods__'
171 >>>
172
173Instead, you can get the same information from the list type:
174
175 >>> pprint.pprint(dir(list)) # like list.__dict__.keys(), but sorted
176 ['__add__',
177 '__class__',
178 '__contains__',
179 '__delattr__',
180 '__delitem__',
Guido van Rossum7b9144b2001-10-09 19:39:46 +0000181 '__delslice__',
Tim Peters80440552002-02-19 04:25:19 +0000182 '__doc__',
Tim Peters95c99e52001-09-03 01:24:30 +0000183 '__eq__',
184 '__ge__',
Guido van Rossum867a8d22001-09-21 19:29:08 +0000185 '__getattribute__',
Tim Peters95c99e52001-09-03 01:24:30 +0000186 '__getitem__',
187 '__getslice__',
188 '__gt__',
189 '__hash__',
190 '__iadd__',
191 '__imul__',
192 '__init__',
Raymond Hettinger14bd6de2002-05-31 21:40:38 +0000193 '__iter__',
Tim Peters95c99e52001-09-03 01:24:30 +0000194 '__le__',
195 '__len__',
196 '__lt__',
197 '__mul__',
198 '__ne__',
199 '__new__',
Guido van Rossum3926a632001-09-25 16:25:58 +0000200 '__reduce__',
Guido van Rossumc53f0092003-02-18 22:05:12 +0000201 '__reduce_ex__',
Tim Peters95c99e52001-09-03 01:24:30 +0000202 '__repr__',
Raymond Hettingeraf28e4b2003-11-08 12:39:53 +0000203 '__reversed__',
Tim Peters95c99e52001-09-03 01:24:30 +0000204 '__rmul__',
205 '__setattr__',
206 '__setitem__',
207 '__setslice__',
208 '__str__',
209 'append',
210 'count',
211 'extend',
212 'index',
213 'insert',
214 'pop',
215 'remove',
216 'reverse',
Raymond Hettinger64958a12003-12-17 20:43:33 +0000217 'sort']
Tim Peters95c99e52001-09-03 01:24:30 +0000218
219The new introspection API gives more information than the old one: in
220addition to the regular methods, it also shows the methods that are
221normally 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
234This is just like it is for user-defined classes.
235"""
236
237test_4 = """
238
239Static methods and class methods
240
241The new introspection API makes it possible to add static methods and class
242methods. Static methods are easy to describe: they behave pretty much like
243static methods in C++ or Java. Here's an example:
244
245 >>> class C:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000246 ...
Guido van Rossum5a8a0372005-01-16 00:25:31 +0000247 ... @staticmethod
Tim Peters95c99e52001-09-03 01:24:30 +0000248 ... def foo(x, y):
Guido van Rossum7131f842007-02-09 20:13:25 +0000249 ... print("staticmethod", x, y)
Tim Peters95c99e52001-09-03 01:24:30 +0000250
251 >>> C.foo(1, 2)
252 staticmethod 1 2
253 >>> c = C()
254 >>> c.foo(1, 2)
255 staticmethod 1 2
256
257Class methods use a similar pattern to declare methods that receive an
258implicit first argument that is the *class* for which they are invoked.
259
260 >>> class C:
Guido van Rossum5a8a0372005-01-16 00:25:31 +0000261 ... @classmethod
Tim Peters95c99e52001-09-03 01:24:30 +0000262 ... def foo(cls, y):
Guido van Rossum7131f842007-02-09 20:13:25 +0000263 ... print("classmethod", cls, y)
Tim Peters95c99e52001-09-03 01:24:30 +0000264
265 >>> C.foo(1)
Thomas Wouters28bc7682006-04-15 09:03:16 +0000266 classmethod <class 'test.test_descrtut.C'> 1
Tim Peters95c99e52001-09-03 01:24:30 +0000267 >>> c = C()
268 >>> c.foo(1)
Thomas Wouters28bc7682006-04-15 09:03:16 +0000269 classmethod <class 'test.test_descrtut.C'> 1
Tim Peters95c99e52001-09-03 01:24:30 +0000270
271 >>> class D(C):
272 ... pass
273
274 >>> D.foo(1)
Thomas Wouters28bc7682006-04-15 09:03:16 +0000275 classmethod <class 'test.test_descrtut.D'> 1
Tim Peters95c99e52001-09-03 01:24:30 +0000276 >>> d = D()
277 >>> d.foo(1)
Thomas Wouters28bc7682006-04-15 09:03:16 +0000278 classmethod <class 'test.test_descrtut.D'> 1
Tim Peters95c99e52001-09-03 01:24:30 +0000279
280This prints "classmethod __main__.D 1" both times; in other words, the
281class passed as the first argument of foo() is the class involved in the
282call, not the class involved in the definition of foo().
283
284But notice this:
285
286 >>> class E(C):
Guido van Rossum5a8a0372005-01-16 00:25:31 +0000287 ... @classmethod
Tim Peters95c99e52001-09-03 01:24:30 +0000288 ... def foo(cls, y): # override C.foo
Guido van Rossum7131f842007-02-09 20:13:25 +0000289 ... print("E.foo() called")
Tim Peters95c99e52001-09-03 01:24:30 +0000290 ... C.foo(y)
Tim Peters95c99e52001-09-03 01:24:30 +0000291
292 >>> E.foo(1)
293 E.foo() called
Thomas Wouters28bc7682006-04-15 09:03:16 +0000294 classmethod <class 'test.test_descrtut.C'> 1
Tim Peters95c99e52001-09-03 01:24:30 +0000295 >>> e = E()
296 >>> e.foo(1)
297 E.foo() called
Thomas Wouters28bc7682006-04-15 09:03:16 +0000298 classmethod <class 'test.test_descrtut.C'> 1
Tim Peters95c99e52001-09-03 01:24:30 +0000299
300In this example, the call to C.foo() from E.foo() will see class C as its
301first argument, not class E. This is to be expected, since the call
302specifies the class C. But it stresses the difference between these class
303methods and methods defined in metaclasses (where an upcall to a metamethod
304would pass the target class as an explicit first argument).
305"""
306
307test_5 = """
308
309Attributes defined by get/set methods
310
311
Guido van Rossum8bce4ac2001-09-06 21:56:42 +0000312 >>> class property(object):
Tim Peters95c99e52001-09-03 01:24:30 +0000313 ...
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
326Now let's define a class with an attribute x defined by a pair of methods,
327getx() and 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 ...
Guido van Rossum8bce4ac2001-09-06 21:56:42 +0000341 ... x = property(getx, setx)
Tim Peters95c99e52001-09-03 01:24:30 +0000342
343Here's a small demonstration:
344
345 >>> a = C()
346 >>> a.x = 10
Guido van Rossum7131f842007-02-09 20:13:25 +0000347 >>> print(a.x)
Tim Peters95c99e52001-09-03 01:24:30 +0000348 10
349 >>> a.x = -10
Guido van Rossum7131f842007-02-09 20:13:25 +0000350 >>> print(a.x)
Tim Peters95c99e52001-09-03 01:24:30 +0000351 0
352 >>>
353
Guido van Rossum8bce4ac2001-09-06 21:56:42 +0000354Hmm -- property is builtin now, so let's try it that way too.
Tim Peters95c99e52001-09-03 01:24:30 +0000355
Guido van Rossum8bce4ac2001-09-06 21:56:42 +0000356 >>> del property # unmask the builtin
357 >>> property
358 <type 'property'>
Tim Peters95c99e52001-09-03 01:24:30 +0000359
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
Guido van Rossum8bce4ac2001-09-06 21:56:42 +0000368 ... x = property(getx, setx)
Tim Peters95c99e52001-09-03 01:24:30 +0000369
370
371 >>> a = C()
372 >>> a.x = 10
Guido van Rossum7131f842007-02-09 20:13:25 +0000373 >>> print(a.x)
Tim Peters95c99e52001-09-03 01:24:30 +0000374 10
375 >>> a.x = -10
Guido van Rossum7131f842007-02-09 20:13:25 +0000376 >>> print(a.x)
Tim Peters95c99e52001-09-03 01:24:30 +0000377 0
378 >>>
379"""
380
381test_6 = """
382
383Method resolution order
384
385This example is implicit in the writeup.
386
Thomas Wouters28bc7682006-04-15 09:03:16 +0000387>>> class A: # implicit new-style class
Tim Peters95c99e52001-09-03 01:24:30 +0000388... def save(self):
Guido van Rossum7131f842007-02-09 20:13:25 +0000389... print("called A.save()")
Tim Peters95c99e52001-09-03 01:24:30 +0000390>>> class B(A):
391... pass
392>>> class C(A):
393... def save(self):
Guido van Rossum7131f842007-02-09 20:13:25 +0000394... print("called C.save()")
Tim Peters95c99e52001-09-03 01:24:30 +0000395>>> class D(B, C):
396... pass
397
398>>> D().save()
Thomas Wouters28bc7682006-04-15 09:03:16 +0000399called C.save()
Tim Peters95c99e52001-09-03 01:24:30 +0000400
Thomas Wouters28bc7682006-04-15 09:03:16 +0000401>>> class A(object): # explicit new-style class
Tim Peters95c99e52001-09-03 01:24:30 +0000402... def save(self):
Guido van Rossum7131f842007-02-09 20:13:25 +0000403... print("called A.save()")
Tim Peters95c99e52001-09-03 01:24:30 +0000404>>> class B(A):
405... pass
406>>> class C(A):
407... def save(self):
Guido van Rossum7131f842007-02-09 20:13:25 +0000408... print("called C.save()")
Tim Peters95c99e52001-09-03 01:24:30 +0000409>>> class D(B, C):
410... pass
411
412>>> D().save()
413called C.save()
414"""
415
416class A(object):
417 def m(self):
418 return "A"
419
420class B(A):
421 def m(self):
422 return "B" + super(B, self).m()
423
424class C(A):
425 def m(self):
426 return "C" + super(C, self).m()
427
428class D(C, B):
429 def m(self):
430 return "D" + super(D, self).m()
431
432
433test_7 = """
434
435Cooperative methods and "super"
436
Guido van Rossum7131f842007-02-09 20:13:25 +0000437>>> print(D().m()) # "DCBA"
Tim Peters95c99e52001-09-03 01:24:30 +0000438DCBA
439"""
440
441test_8 = """
442
443Backwards incompatibilities
444
445>>> class A:
446... def foo(self):
Guido van Rossum7131f842007-02-09 20:13:25 +0000447... print("called A.foo()")
Tim Peters95c99e52001-09-03 01:24:30 +0000448
449>>> class B(A):
450... pass
451
452>>> class C(A):
453... def foo(self):
454... B.foo(self)
455
456>>> C().foo()
457Traceback (most recent call last):
458 ...
459TypeError: unbound method foo() must be called with B instance as first argument (got C instance instead)
460
461>>> class C(A):
462... def foo(self):
463... A.foo(self)
464>>> C().foo()
465called A.foo()
466"""
467
468__test__ = {"tut1": test_1,
469 "tut2": test_2,
470 "tut3": test_3,
471 "tut4": test_4,
472 "tut5": test_5,
473 "tut6": test_6,
474 "tut7": test_7,
475 "tut8": test_8}
476
477# Magic test name that regrtest.py invokes *after* importing this module.
478# This worms around a bootstrap problem.
479# Note that doctest and regrtest both look in sys.argv for a "-v" argument,
480# so this works as expected in both ways of running regrtest.
Tim Petersa0a62222001-09-09 06:12:01 +0000481def test_main(verbose=None):
482 # Obscure: import this module as test.test_descrtut instead of as
483 # plain test_descrtut because the name of this module works its way
484 # into the doctest examples, and unless the full test.test_descrtut
485 # business is used the name can change depending on how the test is
486 # invoked.
Barry Warsaw04f357c2002-07-23 19:04:11 +0000487 from test import test_support, test_descrtut
488 test_support.run_doctest(test_descrtut, verbose)
Tim Peters95c99e52001-09-03 01:24:30 +0000489
490# This part isn't needed for regrtest, but for running the test directly.
491if __name__ == "__main__":
Tim Petersa0a62222001-09-09 06:12:01 +0000492 test_main(1)