Tim Peters | 95c99e5 | 2001-09-03 01:24:30 +0000 | [diff] [blame] | 1 | # 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 | |
| 11 | from test_support import sortdict |
| 12 | import pprint |
| 13 | |
| 14 | class 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 | |
| 35 | test_1 = """ |
| 36 | |
| 37 | Here's the new type at work: |
| 38 | |
| 39 | >>> print defaultdict # show our type |
Guido van Rossum | a4cb788 | 2001-09-25 03:56:29 +0000 | [diff] [blame] | 40 | <class 'test.test_descrtut.defaultdict'> |
Tim Peters | 95c99e5 | 2001-09-03 01:24:30 +0000 | [diff] [blame] | 41 | >>> 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 Rossum | a4cb788 | 2001-09-25 03:56:29 +0000 | [diff] [blame] | 47 | <class 'test.test_descrtut.defaultdict'> |
Tim Peters | 95c99e5 | 2001-09-03 01:24:30 +0000 | [diff] [blame] | 48 | >>> print a.__class__ # show its class |
Guido van Rossum | a4cb788 | 2001-09-25 03:56:29 +0000 | [diff] [blame] | 49 | <class 'test.test_descrtut.defaultdict'> |
Tim Peters | 95c99e5 | 2001-09-03 01:24:30 +0000 | [diff] [blame] | 50 | >>> 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 | |
| 64 | We can also use the new type in contexts where classic only allows "real" |
| 65 | dictionaries, such as the locals/globals dictionaries for the exec |
| 66 | statement 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 | |
| 81 | However, our __getitem__() method is not used for variable access by the |
| 82 | interpreter: |
| 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 | |
| 91 | Now I'll show that defaultdict instances have dynamic instance variables, |
| 92 | just 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 Peters | 5d2b77c | 2001-09-03 05:47:38 +0000 | [diff] [blame] | 100 | >>> 'default' in dir(a) |
| 101 | 1 |
Tim Peters | 95c99e5 | 2001-09-03 01:24:30 +0000 | [diff] [blame] | 102 | >>> a.x1 = 100 |
| 103 | >>> a.x2 = 200 |
| 104 | >>> print a.x1 |
| 105 | 100 |
Tim Peters | 5d2b77c | 2001-09-03 05:47:38 +0000 | [diff] [blame] | 106 | >>> d = dir(a) |
| 107 | >>> 'default' in d and 'x1' in d and 'x2' in d |
| 108 | 1 |
Tim Peters | 95c99e5 | 2001-09-03 01:24:30 +0000 | [diff] [blame] | 109 | >>> print a.__dict__ |
| 110 | {'default': -1000, 'x2': 200, 'x1': 100} |
| 111 | >>> |
| 112 | """ |
| 113 | |
| 114 | class 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 | |
| 137 | test_2 = """ |
| 138 | |
| 139 | The __slots__ declaration takes a list of instance variables, and reserves |
| 140 | space for exactly these in the instance. When __slots__ is used, other |
| 141 | instance 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 | |
| 157 | test_3 = """ |
| 158 | |
| 159 | Introspecting instances of built-in types |
| 160 | |
| 161 | For 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 | |
| 177 | Under 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 | |
| 185 | Instead, 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 Rossum | 7b9144b | 2001-10-09 19:39:46 +0000 | [diff] [blame^] | 193 | '__delslice__', |
Tim Peters | 95c99e5 | 2001-09-03 01:24:30 +0000 | [diff] [blame] | 194 | '__eq__', |
| 195 | '__ge__', |
Guido van Rossum | 867a8d2 | 2001-09-21 19:29:08 +0000 | [diff] [blame] | 196 | '__getattribute__', |
Tim Peters | 95c99e5 | 2001-09-03 01:24:30 +0000 | [diff] [blame] | 197 | '__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 Rossum | 3926a63 | 2001-09-25 16:25:58 +0000 | [diff] [blame] | 210 | '__reduce__', |
Tim Peters | 95c99e5 | 2001-09-03 01:24:30 +0000 | [diff] [blame] | 211 | '__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 | |
| 227 | The new introspection API gives more information than the old one: in |
| 228 | addition to the regular methods, it also shows the methods that are |
| 229 | normally 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 | |
| 242 | This is just like it is for user-defined classes. |
| 243 | """ |
| 244 | |
| 245 | test_4 = """ |
| 246 | |
| 247 | Static methods and class methods |
| 248 | |
| 249 | The new introspection API makes it possible to add static methods and class |
| 250 | methods. Static methods are easy to describe: they behave pretty much like |
| 251 | static 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 | |
| 265 | Class methods use a similar pattern to declare methods that receive an |
| 266 | implicit 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 Peters | 90ba8d9 | 2001-09-09 01:21:31 +0000 | [diff] [blame] | 274 | classmethod test.test_descrtut.C 1 |
Tim Peters | 95c99e5 | 2001-09-03 01:24:30 +0000 | [diff] [blame] | 275 | >>> c = C() |
| 276 | >>> c.foo(1) |
Tim Peters | 90ba8d9 | 2001-09-09 01:21:31 +0000 | [diff] [blame] | 277 | classmethod test.test_descrtut.C 1 |
Tim Peters | 95c99e5 | 2001-09-03 01:24:30 +0000 | [diff] [blame] | 278 | |
| 279 | >>> class D(C): |
| 280 | ... pass |
| 281 | |
| 282 | >>> D.foo(1) |
Tim Peters | 90ba8d9 | 2001-09-09 01:21:31 +0000 | [diff] [blame] | 283 | classmethod test.test_descrtut.D 1 |
Tim Peters | 95c99e5 | 2001-09-03 01:24:30 +0000 | [diff] [blame] | 284 | >>> d = D() |
| 285 | >>> d.foo(1) |
Tim Peters | 90ba8d9 | 2001-09-09 01:21:31 +0000 | [diff] [blame] | 286 | classmethod test.test_descrtut.D 1 |
Tim Peters | 95c99e5 | 2001-09-03 01:24:30 +0000 | [diff] [blame] | 287 | |
| 288 | This prints "classmethod __main__.D 1" both times; in other words, the |
| 289 | class passed as the first argument of foo() is the class involved in the |
| 290 | call, not the class involved in the definition of foo(). |
| 291 | |
| 292 | But 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 Peters | 90ba8d9 | 2001-09-09 01:21:31 +0000 | [diff] [blame] | 302 | classmethod test.test_descrtut.C 1 |
Tim Peters | 95c99e5 | 2001-09-03 01:24:30 +0000 | [diff] [blame] | 303 | >>> e = E() |
| 304 | >>> e.foo(1) |
| 305 | E.foo() called |
Tim Peters | 90ba8d9 | 2001-09-09 01:21:31 +0000 | [diff] [blame] | 306 | classmethod test.test_descrtut.C 1 |
Tim Peters | 95c99e5 | 2001-09-03 01:24:30 +0000 | [diff] [blame] | 307 | |
| 308 | In this example, the call to C.foo() from E.foo() will see class C as its |
| 309 | first argument, not class E. This is to be expected, since the call |
| 310 | specifies the class C. But it stresses the difference between these class |
| 311 | methods and methods defined in metaclasses (where an upcall to a metamethod |
| 312 | would pass the target class as an explicit first argument). |
| 313 | """ |
| 314 | |
| 315 | test_5 = """ |
| 316 | |
| 317 | Attributes defined by get/set methods |
| 318 | |
| 319 | |
Guido van Rossum | 8bce4ac | 2001-09-06 21:56:42 +0000 | [diff] [blame] | 320 | >>> class property(object): |
Tim Peters | 95c99e5 | 2001-09-03 01:24:30 +0000 | [diff] [blame] | 321 | ... |
| 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 | |
| 334 | Now let's define a class with an attribute x defined by a pair of methods, |
| 335 | getx() 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 Rossum | 8bce4ac | 2001-09-06 21:56:42 +0000 | [diff] [blame] | 349 | ... x = property(getx, setx) |
Tim Peters | 95c99e5 | 2001-09-03 01:24:30 +0000 | [diff] [blame] | 350 | |
| 351 | Here'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 Rossum | 8bce4ac | 2001-09-06 21:56:42 +0000 | [diff] [blame] | 362 | Hmm -- property is builtin now, so let's try it that way too. |
Tim Peters | 95c99e5 | 2001-09-03 01:24:30 +0000 | [diff] [blame] | 363 | |
Guido van Rossum | 8bce4ac | 2001-09-06 21:56:42 +0000 | [diff] [blame] | 364 | >>> del property # unmask the builtin |
| 365 | >>> property |
| 366 | <type 'property'> |
Tim Peters | 95c99e5 | 2001-09-03 01:24:30 +0000 | [diff] [blame] | 367 | |
| 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 Rossum | 8bce4ac | 2001-09-06 21:56:42 +0000 | [diff] [blame] | 376 | ... x = property(getx, setx) |
Tim Peters | 95c99e5 | 2001-09-03 01:24:30 +0000 | [diff] [blame] | 377 | |
| 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 | |
| 389 | test_6 = """ |
| 390 | |
| 391 | Method resolution order |
| 392 | |
| 393 | This 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() |
| 407 | called 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() |
| 421 | called C.save() |
| 422 | """ |
| 423 | |
| 424 | class A(object): |
| 425 | def m(self): |
| 426 | return "A" |
| 427 | |
| 428 | class B(A): |
| 429 | def m(self): |
| 430 | return "B" + super(B, self).m() |
| 431 | |
| 432 | class C(A): |
| 433 | def m(self): |
| 434 | return "C" + super(C, self).m() |
| 435 | |
| 436 | class D(C, B): |
| 437 | def m(self): |
| 438 | return "D" + super(D, self).m() |
| 439 | |
| 440 | |
| 441 | test_7 = """ |
| 442 | |
| 443 | Cooperative methods and "super" |
| 444 | |
| 445 | >>> print D().m() # "DCBA" |
| 446 | DCBA |
| 447 | """ |
| 448 | |
| 449 | test_8 = """ |
| 450 | |
| 451 | Backwards 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() |
| 465 | Traceback (most recent call last): |
| 466 | ... |
| 467 | TypeError: 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() |
| 473 | called 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 Peters | a0a6222 | 2001-09-09 06:12:01 +0000 | [diff] [blame] | 489 | def 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 Peters | 95c99e5 | 2001-09-03 01:24:30 +0000 | [diff] [blame] | 497 | |
| 498 | # This part isn't needed for regrtest, but for running the test directly. |
| 499 | if __name__ == "__main__": |
Tim Peters | a0a6222 | 2001-09-09 06:12:01 +0000 | [diff] [blame] | 500 | test_main(1) |