test_descrtut.py 11.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
# This contains most of the executable examples from Guido's descr
# tutorial, once at
#
#     http://www.python.org/2.2/descrintro.html
#
# A few examples left implicit in the writeup were fleshed out, a few were
# skipped due to lack of interest (e.g., faking super() by hand isn't
# of much interest anymore), and a few were fiddled to make the output
# deterministic.

11
from test.test_support import sortdict
12 13
import pprint

14
class defaultdict(dict):
15
    def __init__(self, default=None):
16
        dict.__init__(self)
17 18 19 20
        self.default = default

    def __getitem__(self, key):
        try:
21
            return dict.__getitem__(self, key)
22 23 24 25 26 27
        except KeyError:
            return self.default

    def get(self, key, *args):
        if not args:
            args = (self.default,)
28
        return dict.get(self, key, *args)
29 30 31 32 33 34 35 36 37 38 39

    def merge(self, other):
        for key in other:
            if key not in self:
                self[key] = other[key]

test_1 = """

Here's the new type at work:

    >>> print defaultdict               # show our type
40
    <class 'test.test_descrtut.defaultdict'>
41 42 43 44 45 46
    >>> print type(defaultdict)         # its metatype
    <type 'type'>
    >>> a = defaultdict(default=0.0)    # create an instance
    >>> print a                         # show the instance
    {}
    >>> print type(a)                   # show its type
47
    <class 'test.test_descrtut.defaultdict'>
48
    >>> print a.__class__               # show its class
49
    <class 'test.test_descrtut.defaultdict'>
50
    >>> print type(a) is a.__class__    # its type is its class
51
    True
52 53 54 55 56 57 58
    >>> a[1] = 3.25                     # modify the instance
    >>> print a                         # show the new value
    {1: 3.25}
    >>> print a[1]                      # show the new item
    3.25
    >>> print a[0]                      # a non-existant item
    0.0
59
    >>> a.merge({1:100, 2:200})         # use a dict method
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
    >>> print sortdict(a)               # show the result
    {1: 3.25, 2: 200}
    >>>

We can also use the new type in contexts where classic only allows "real"
dictionaries, such as the locals/globals dictionaries for the exec
statement or the built-in function eval():

    >>> def sorted(seq):
    ...     seq.sort()
    ...     return seq
    >>> print sorted(a.keys())
    [1, 2]
    >>> exec "x = 3; print x" in a
    3
    >>> print sorted(a.keys())
    [1, 2, '__builtins__', 'x']
    >>> print a['x']
    3
    >>>

Now I'll show that defaultdict instances have dynamic instance variables,
just like classic classes:

    >>> a.default = -1
    >>> print a["noway"]
    -1
    >>> a.default = -1000
    >>> print a["noway"]
    -1000
90
    >>> 'default' in dir(a)
91
    True
92 93 94 95
    >>> a.x1 = 100
    >>> a.x2 = 200
    >>> print a.x1
    100
96 97
    >>> d = dir(a)
    >>> 'default' in d and 'x1' in d and 'x2' in d
98
    True
99 100
    >>> print sortdict(a.__dict__)
    {'default': -1000, 'x1': 100, 'x2': 200}
101 102 103
    >>>
"""

104
class defaultdict2(dict):
105 106 107
    __slots__ = ['default']

    def __init__(self, default=None):
108
        dict.__init__(self)
109 110 111 112
        self.default = default

    def __getitem__(self, key):
        try:
113
            return dict.__getitem__(self, key)
114 115 116 117 118 119
        except KeyError:
            return self.default

    def get(self, key, *args):
        if not args:
            args = (self.default,)
120
        return dict.get(self, key, *args)
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159

    def merge(self, other):
        for key in other:
            if key not in self:
                self[key] = other[key]

test_2 = """

The __slots__ declaration takes a list of instance variables, and reserves
space for exactly these in the instance. When __slots__ is used, other
instance variables cannot be assigned to:

    >>> a = defaultdict2(default=0.0)
    >>> a[1]
    0.0
    >>> a.default = -1
    >>> a[1]
    -1
    >>> a.x1 = 1
    Traceback (most recent call last):
      File "<stdin>", line 1, in ?
    AttributeError: 'defaultdict2' object has no attribute 'x1'
    >>>

"""

test_3 = """

Introspecting instances of built-in types

For instance of built-in types, x.__class__ is now the same as type(x):

    >>> type([])
    <type 'list'>
    >>> [].__class__
    <type 'list'>
    >>> list
    <type 'list'>
    >>> isinstance([], list)
160
    True
161
    >>> isinstance([], dict)
162
    False
163
    >>> isinstance([], object)
164
    True
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182
    >>>

Under the new proposal, the __methods__ attribute no longer exists:

    >>> [].__methods__
    Traceback (most recent call last):
      File "<stdin>", line 1, in ?
    AttributeError: 'list' object has no attribute '__methods__'
    >>>

Instead, you can get the same information from the list type:

    >>> pprint.pprint(dir(list))    # like list.__dict__.keys(), but sorted
    ['__add__',
     '__class__',
     '__contains__',
     '__delattr__',
     '__delitem__',
183
     '__delslice__',
184
     '__doc__',
185
     '__eq__',
186
     '__format__',
187
     '__ge__',
188
     '__getattribute__',
189 190 191 192 193 194 195
     '__getitem__',
     '__getslice__',
     '__gt__',
     '__hash__',
     '__iadd__',
     '__imul__',
     '__init__',
196
     '__iter__',
197 198 199 200 201 202
     '__le__',
     '__len__',
     '__lt__',
     '__mul__',
     '__ne__',
     '__new__',
203
     '__reduce__',
204
     '__reduce_ex__',
205
     '__repr__',
206
     '__reversed__',
207 208 209 210
     '__rmul__',
     '__setattr__',
     '__setitem__',
     '__setslice__',
Georg Brandl's avatar
Georg Brandl committed
211
     '__sizeof__',
212
     '__str__',
213
     '__subclasshook__',
214 215 216 217 218 219 220 221
     'append',
     'count',
     'extend',
     'index',
     'insert',
     'pop',
     'remove',
     'reverse',
222
     'sort']
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251

The new introspection API gives more information than the old one:  in
addition to the regular methods, it also shows the methods that are
normally invoked through special notations, e.g. __iadd__ (+=), __len__
(len), __ne__ (!=). You can invoke any method from this list directly:

    >>> a = ['tic', 'tac']
    >>> list.__len__(a)          # same as len(a)
    2
    >>> a.__len__()              # ditto
    2
    >>> list.append(a, 'toe')    # same as a.append('toe')
    >>> a
    ['tic', 'tac', 'toe']
    >>>

This is just like it is for user-defined classes.
"""

test_4 = """

Static methods and class methods

The new introspection API makes it possible to add static methods and class
methods. Static methods are easy to describe: they behave pretty much like
static methods in C++ or Java. Here's an example:

    >>> class C:
    ...
Guido van Rossum's avatar
Guido van Rossum committed
252
    ...     @staticmethod
253 254 255 256 257 258 259 260 261 262 263 264 265
    ...     def foo(x, y):
    ...         print "staticmethod", x, y

    >>> C.foo(1, 2)
    staticmethod 1 2
    >>> c = C()
    >>> c.foo(1, 2)
    staticmethod 1 2

Class methods use a similar pattern to declare methods that receive an
implicit first argument that is the *class* for which they are invoked.

    >>> class C:
Guido van Rossum's avatar
Guido van Rossum committed
266
    ...     @classmethod
267 268 269 270
    ...     def foo(cls, y):
    ...         print "classmethod", cls, y

    >>> C.foo(1)
271
    classmethod test.test_descrtut.C 1
272 273
    >>> c = C()
    >>> c.foo(1)
274
    classmethod test.test_descrtut.C 1
275 276 277 278 279

    >>> class D(C):
    ...     pass

    >>> D.foo(1)
280
    classmethod test.test_descrtut.D 1
281 282
    >>> d = D()
    >>> d.foo(1)
283
    classmethod test.test_descrtut.D 1
284 285 286 287 288 289 290 291

This prints "classmethod __main__.D 1" both times; in other words, the
class passed as the first argument of foo() is the class involved in the
call, not the class involved in the definition of foo().

But notice this:

    >>> class E(C):
Guido van Rossum's avatar
Guido van Rossum committed
292
    ...     @classmethod
293 294 295 296 297 298
    ...     def foo(cls, y): # override C.foo
    ...         print "E.foo() called"
    ...         C.foo(y)

    >>> E.foo(1)
    E.foo() called
299
    classmethod test.test_descrtut.C 1
300 301 302
    >>> e = E()
    >>> e.foo(1)
    E.foo() called
303
    classmethod test.test_descrtut.C 1
304 305 306 307 308 309 310 311 312 313 314 315 316

In this example, the call to C.foo() from E.foo() will see class C as its
first argument, not class E. This is to be expected, since the call
specifies the class C. But it stresses the difference between these class
methods and methods defined in metaclasses (where an upcall to a metamethod
would pass the target class as an explicit first argument).
"""

test_5 = """

Attributes defined by get/set methods


317
    >>> class property(object):
318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345
    ...
    ...     def __init__(self, get, set=None):
    ...         self.__get = get
    ...         self.__set = set
    ...
    ...     def __get__(self, inst, type=None):
    ...         return self.__get(inst)
    ...
    ...     def __set__(self, inst, value):
    ...         if self.__set is None:
    ...             raise AttributeError, "this attribute is read-only"
    ...         return self.__set(inst, value)

Now let's define a class with an attribute x defined by a pair of methods,
getx() and and setx():

    >>> class C(object):
    ...
    ...     def __init__(self):
    ...         self.__x = 0
    ...
    ...     def getx(self):
    ...         return self.__x
    ...
    ...     def setx(self, x):
    ...         if x < 0: x = 0
    ...         self.__x = x
    ...
346
    ...     x = property(getx, setx)
347 348 349 350 351 352 353 354 355 356 357 358

Here's a small demonstration:

    >>> a = C()
    >>> a.x = 10
    >>> print a.x
    10
    >>> a.x = -10
    >>> print a.x
    0
    >>>

359
Hmm -- property is builtin now, so let's try it that way too.
360

361 362 363
    >>> del property  # unmask the builtin
    >>> property
    <type 'property'>
364 365 366 367 368 369 370 371 372

    >>> class C(object):
    ...     def __init__(self):
    ...         self.__x = 0
    ...     def getx(self):
    ...         return self.__x
    ...     def setx(self, x):
    ...         if x < 0: x = 0
    ...         self.__x = x
373
    ...     x = property(getx, setx)
374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485


    >>> a = C()
    >>> a.x = 10
    >>> print a.x
    10
    >>> a.x = -10
    >>> print a.x
    0
    >>>
"""

test_6 = """

Method resolution order

This example is implicit in the writeup.

>>> class A:    # classic class
...     def save(self):
...         print "called A.save()"
>>> class B(A):
...     pass
>>> class C(A):
...     def save(self):
...         print "called C.save()"
>>> class D(B, C):
...     pass

>>> D().save()
called A.save()

>>> class A(object):  # new class
...     def save(self):
...         print "called A.save()"
>>> class B(A):
...     pass
>>> class C(A):
...     def save(self):
...         print "called C.save()"
>>> class D(B, C):
...     pass

>>> D().save()
called C.save()
"""

class A(object):
    def m(self):
        return "A"

class B(A):
    def m(self):
        return "B" + super(B, self).m()

class C(A):
    def m(self):
        return "C" + super(C, self).m()

class D(C, B):
    def m(self):
        return "D" + super(D, self).m()


test_7 = """

Cooperative methods and "super"

>>> print D().m() # "DCBA"
DCBA
"""

test_8 = """

Backwards incompatibilities

>>> class A:
...     def foo(self):
...         print "called A.foo()"

>>> class B(A):
...     pass

>>> class C(A):
...     def foo(self):
...         B.foo(self)

>>> C().foo()
Traceback (most recent call last):
 ...
TypeError: unbound method foo() must be called with B instance as first argument (got C instance instead)

>>> class C(A):
...     def foo(self):
...         A.foo(self)
>>> C().foo()
called A.foo()
"""

__test__ = {"tut1": test_1,
            "tut2": test_2,
            "tut3": test_3,
            "tut4": test_4,
            "tut5": test_5,
            "tut6": test_6,
            "tut7": test_7,
            "tut8": test_8}

# Magic test name that regrtest.py invokes *after* importing this module.
# This worms around a bootstrap problem.
# Note that doctest and regrtest both look in sys.argv for a "-v" argument,
# so this works as expected in both ways of running regrtest.
486 487 488 489 490 491
def test_main(verbose=None):
    # Obscure:  import this module as test.test_descrtut instead of as
    # plain test_descrtut because the name of this module works its way
    # into the doctest examples, and unless the full test.test_descrtut
    # business is used the name can change depending on how the test is
    # invoked.
492 493
    from test import test_support, test_descrtut
    test_support.run_doctest(test_descrtut, verbose)
494 495 496

# This part isn't needed for regrtest, but for running the test directly.
if __name__ == "__main__":
497
    test_main(1)