DESCRIPTION.rst 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. * New in 0.8: Source and tests are compatible with Python 3 (w/o ``setup.py``)
  2. * 0.8.1: setup.py is now compatible with Python 3 as well
  3. * New in 0.7: `Multiple Types or Objects`_
  4. * New in 0.6: `Inspection and Extension`_, and thread-safe method registration
  5. The ``simplegeneric`` module lets you define simple single-dispatch
  6. generic functions, akin to Python's built-in generic functions like
  7. ``len()``, ``iter()`` and so on. However, instead of using
  8. specially-named methods, these generic functions use simple lookup
  9. tables, akin to those used by e.g. ``pickle.dump()`` and other
  10. generic functions found in the Python standard library.
  11. As you can see from the above examples, generic functions are actually
  12. quite common in Python already, but there is no standard way to create
  13. simple ones. This library attempts to fill that gap, as generic
  14. functions are an `excellent alternative to the Visitor pattern`_, as
  15. well as being a great substitute for most common uses of adaptation.
  16. This library tries to be the simplest possible implementation of generic
  17. functions, and it therefore eschews the use of multiple or predicate
  18. dispatch, as well as avoiding speedup techniques such as C dispatching
  19. or code generation. But it has absolutely no dependencies, other than
  20. Python 2.4, and the implementation is just a single Python module of
  21. less than 100 lines.
  22. Usage
  23. -----
  24. Defining and using a generic function is straightforward::
  25. >>> from simplegeneric import generic
  26. >>> @generic
  27. ... def move(item, target):
  28. ... """Default implementation goes here"""
  29. ... print("what you say?!")
  30. >>> @move.when_type(int)
  31. ... def move_int(item, target):
  32. ... print("In AD %d, %s was beginning." % (item, target))
  33. >>> @move.when_type(str)
  34. ... def move_str(item, target):
  35. ... print("How are you %s!!" % item)
  36. ... print("All your %s are belong to us." % (target,))
  37. >>> zig = object()
  38. >>> @move.when_object(zig)
  39. ... def move_zig(item, target):
  40. ... print("You know what you %s." % (target,))
  41. ... print("For great justice!")
  42. >>> move(2101, "war")
  43. In AD 2101, war was beginning.
  44. >>> move("gentlemen", "base")
  45. How are you gentlemen!!
  46. All your base are belong to us.
  47. >>> move(zig, "doing")
  48. You know what you doing.
  49. For great justice!
  50. >>> move(27.0, 56.2)
  51. what you say?!
  52. Inheritance and Allowed Types
  53. -----------------------------
  54. Defining multiple methods for the same type or object is an error::
  55. >>> @move.when_type(str)
  56. ... def this_is_wrong(item, target):
  57. ... pass
  58. Traceback (most recent call last):
  59. ...
  60. TypeError: <function move...> already has method for type <...'str'>
  61. >>> @move.when_object(zig)
  62. ... def this_is_wrong(item, target): pass
  63. Traceback (most recent call last):
  64. ...
  65. TypeError: <function move...> already has method for object <object ...>
  66. And the ``when_type()`` decorator only accepts classes or types::
  67. >>> @move.when_type(23)
  68. ... def move_23(item, target):
  69. ... print("You have no chance to survive!")
  70. Traceback (most recent call last):
  71. ...
  72. TypeError: 23 is not a type or class
  73. Methods defined for supertypes are inherited following MRO order::
  74. >>> class MyString(str):
  75. ... """String subclass"""
  76. >>> move(MyString("ladies"), "drinks")
  77. How are you ladies!!
  78. All your drinks are belong to us.
  79. Classic class instances are also supported (although the lookup process
  80. is slower than for new-style instances)::
  81. >>> class X: pass
  82. >>> class Y(X): pass
  83. >>> @move.when_type(X)
  84. ... def move_x(item, target):
  85. ... print("Someone set us up the %s!!!" % (target,))
  86. >>> move(X(), "bomb")
  87. Someone set us up the bomb!!!
  88. >>> move(Y(), "dance")
  89. Someone set us up the dance!!!
  90. Multiple Types or Objects
  91. -------------------------
  92. As a convenience, you can now pass more than one type or object to the
  93. registration methods::
  94. >>> @generic
  95. ... def isbuiltin(ob):
  96. ... return False
  97. >>> @isbuiltin.when_type(int, str, float, complex, type)
  98. ... @isbuiltin.when_object(None, Ellipsis)
  99. ... def yes(ob):
  100. ... return True
  101. >>> isbuiltin(1)
  102. True
  103. >>> isbuiltin(object)
  104. True
  105. >>> isbuiltin(object())
  106. False
  107. >>> isbuiltin(X())
  108. False
  109. >>> isbuiltin(None)
  110. True
  111. >>> isbuiltin(Ellipsis)
  112. True
  113. Defaults and Docs
  114. -----------------
  115. You can obtain a function's default implementation using its ``default``
  116. attribute::
  117. >>> @move.when_type(Y)
  118. ... def move_y(item, target):
  119. ... print("Someone set us up the %s!!!" % (target,))
  120. ... move.default(item, target)
  121. >>> move(Y(), "dance")
  122. Someone set us up the dance!!!
  123. what you say?!
  124. ``help()`` and other documentation tools see generic functions as normal
  125. function objects, with the same name, attributes, docstring, and module as
  126. the prototype/default function::
  127. >>> help(move)
  128. Help on function move:
  129. ...
  130. move(*args, **kw)
  131. Default implementation goes here
  132. ...
  133. Inspection and Extension
  134. ------------------------
  135. You can find out if a generic function has a method for a type or object using
  136. the ``has_object()`` and ``has_type()`` methods::
  137. >>> move.has_object(zig)
  138. True
  139. >>> move.has_object(42)
  140. False
  141. >>> move.has_type(X)
  142. True
  143. >>> move.has_type(float)
  144. False
  145. Note that ``has_type()`` only queries whether there is a method registered for
  146. the *exact* type, not subtypes or supertypes::
  147. >>> class Z(X): pass
  148. >>> move.has_type(Z)
  149. False
  150. You can create a generic function that "inherits" from an existing generic
  151. function by calling ``generic()`` on the existing function::
  152. >>> move2 = generic(move)
  153. >>> move(2101, "war")
  154. In AD 2101, war was beginning.
  155. Any methods added to the new generic function override *all* methods in the
  156. "base" function::
  157. >>> @move2.when_type(X)
  158. ... def move2_X(item, target):
  159. ... print("You have no chance to survive make your %s!" % (target,))
  160. >>> move2(X(), "time")
  161. You have no chance to survive make your time!
  162. >>> move2(Y(), "time")
  163. You have no chance to survive make your time!
  164. Notice that even though ``move()`` has a method for type ``Y``, the method
  165. defined for ``X`` in ``move2()`` takes precedence. This is because the
  166. ``move`` function is used as the ``default`` method of ``move2``, and ``move2``
  167. has no method for type ``Y``::
  168. >>> move2.default is move
  169. True
  170. >>> move.has_type(Y)
  171. True
  172. >>> move2.has_type(Y)
  173. False
  174. Limitations
  175. -----------
  176. * The first argument is always used for dispatching, and it must always be
  177. passed *positionally* when the function is called.
  178. * Documentation tools don't see the function's original argument signature, so
  179. you have to describe it in the docstring.
  180. * If you have optional arguments, you must duplicate them on every method in
  181. order for them to work correctly. (On the plus side, it means you can have
  182. different defaults or required arguments for each method, although relying on
  183. that quirk probably isn't a good idea.)
  184. These restrictions may be lifted in later releases, if I feel the need. They
  185. would require runtime code generation the way I do it in ``RuleDispatch``,
  186. however, which is somewhat of a pain. (Alternately I could use the
  187. ``BytecodeAssembler`` package to do the code generation, as that's a lot easier
  188. to use than string-based code generation, but that would introduce more
  189. dependencies, and I'm trying to keep this simple so I can just
  190. toss it into Chandler without a big footprint increase.)
  191. .. _excellent alternative to the Visitor pattern: http://peak.telecommunity.com/DevCenter/VisitorRevisited