README.txt 7.7 KB

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