test_descrtut.py 12 KB

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