You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
``variants`` is a library that provides syntactic sugar for creating alternate forms of functions and other callables, in the same way that alternate constructors are class methods that provide alternate forms of the constructor function.
20
21
21
-
Library that enables the creation of altern constructor-like variant forms for arbitrary functions.
22
+
To create a function with variants, simply decorate the primary form with ``@variants.primary``, which then adds the ``.variant`` decorator to the original function, which can be used to register new variants. Here is a simple example of a function that prints text, with variants that specify the source of the text to print:
22
23
24
+
.. code-block:: python
23
25
24
-
* Free software: Apache Software License 2.0
25
-
* Documentation: https://variants.readthedocs.io.
26
+
import variants
26
27
28
+
@variants.primary
29
+
defprint_text(txt):
30
+
print(txt)
27
31
28
-
Features
29
-
--------
32
+
@print_text.variant('from_file')
33
+
defprint_text(fobj):
34
+
print_text(fobj.read())
35
+
36
+
@print_text.variant('from_filepath')
37
+
defprint_text(fpath):
38
+
withopen(fpath, 'r') as f:
39
+
print_text.from_file(f)
40
+
41
+
@print_text.variant('from_url')
42
+
defprint_text(url):
43
+
import requests
44
+
r = requests.get(url)
45
+
print_text(r.text)
46
+
47
+
48
+
``print_text`` and its variants can be used as such:
49
+
50
+
.. code-block:: python
51
+
52
+
print_text('Hello, world!') # Hello, world!
53
+
54
+
# Create a text file
55
+
withopen('hello_world.txt', 'w') as f:
56
+
f.write('Hello, world (from file)')
57
+
58
+
# Print from an open file object
59
+
withopen('hello_world.txt', 'r') as f:
60
+
print_text.from_file(f) # Hello, world (from file)
61
+
62
+
# Print from the path to a file object
63
+
print_text.from_filepath('hello_world.txt') # Hello, world (from file)
0 commit comments