@@ -63,8 +63,72 @@ To create a function with variants, simply decorate the primary form with ``@var
63
63
print_text.from_url(hw_url) # Hello, world! (from url)
64
64
65
65
66
+ Differences from singledispatch
67
+ -------------------------------
68
+
69
+ While ``variants `` and |singledispatch |_ are both intended to provide alternative implementations
70
+ to a primary function, the overall aims are slightly different. ``singledispatch `` transparently
71
+ dispatches to variant functions based on the *type * of the argument, whereas ``variants `` provides
72
+ *explicit * alternative forms of the function. Note that in the above example, both
73
+ ``print_text.from_filepath `` and ``print_text.from_url `` take a string, one representing a file
74
+ path and one representing a URL.
75
+
76
+ Additionally, the ``variants `` is compatible with ``singledispatch ``, so you can have the best of
77
+ both worlds; an example that uses both:
78
+
79
+
80
+ .. code-block :: python
81
+
82
+ @variants.primary
83
+ @singledispatch
84
+ def add (x , y ):
85
+ return x + y
86
+
87
+ @add.variant (' from_list' )
88
+ @add.register (list )
89
+ def add (x , y ):
90
+ return x + [y]
91
+
92
+ Which then automatically dispatches between named variants based on type:
93
+
94
+ .. code-block :: python
95
+
96
+ >> > add(1 , 2 )
97
+ 3
98
+ >> > add([1 ], 2 )
99
+ [1 , 2 ]
100
+
101
+ But also exposes the explicit variant functions:
102
+
103
+ .. code-block :: python
104
+
105
+ >> > add.from_list([1 ], 2 )
106
+ [1 , 2 ]
107
+ >> > add.from_list()
108
+ 7 @ add.register(list )
109
+ 8 def add (x , y ):
110
+ ---- > 9 return x + [y]
111
+
112
+ TypeError : unsupported operand type (s) for + : ' int' and ' list'
113
+
114
+ It is important to note that the `` variants`` decorators ** must be the outer decorators** .
115
+
116
+
117
+ Installation
118
+ ------------
119
+
120
+ To install variants, run this command in your terminal:
121
+
122
+ .. code-block :: console
123
+
124
+ $ pip install variants
125
+
126
+
66
127
Requirements
67
128
------------
68
129
69
130
This is a library for Python, with support for versions 2.7 and 3.4+.
70
131
132
+ .. |singledispatch | replace :: ``singledispatch ``
133
+ .. _singledispatch : https://docs.python.org/3/library/functools.html#functools.singledispatch
134
+
0 commit comments