File: flow.rst

package info (click to toggle)
python-funcy 2.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 536 kB
  • sloc: python: 2,989; makefile: 140; javascript: 96; sh: 6
file content (238 lines) | stat: -rw-r--r-- 8,158 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
Flow
====

.. decorator:: silent

    Ignore all real exceptions (descendants of :exc:`~py3:exceptions.Exception`). Handy for cleaning data such as user input::


        brand_id = silent(int)(request.GET['brand_id'])
        ids = keep(silent(int), request.GET.getlist('id'))

    And in data import/transform::

        get_greeting = compose(silent(string.lower), re_finder(r'(\w+)!'))
        map(get_greeting, ['a!', ' B!', 'c.'])
        # -> ['a', 'b', None]

    .. note:: Avoid silencing non-primitive functions, use :func:`@ignore()<ignore>` instead and even then be careful not to swallow exceptions unintentionally.


.. decorator:: ignore(errors, default=None)

    Same as :func:`@silent<silent>`, but able to specify ``errors`` to catch and ``default`` to return in case of error caught. ``errors`` can either be exception class or a tuple of them.


.. function:: suppress(*errors)

    A context manager which suppresses given exceptions under its scope::

        with suppress(HttpError):
            # Assume this request can fail, and we are ok with it
            make_http_request()


.. function:: nullcontext(enter_result=None)

    A noop context manager that returns ``enter_result`` from ``__enter__``::

        ctx = nullcontext()
        if threads:
            ctx = op_thread_lock

        with ctx:
            # ... do stuff


.. decorator:: once
               once_per_args
               once_per(*argnames)

    Call function only once, once for every combination of values of its arguments or once for every combination of given arguments. Thread safe. Handy for various initialization purposes::

        # Global initialization
        @once
        def initialize_cache():
            conn = some.Connection(...)
            # ... set up everything

        # Per argument initialization
        @once_per_args
        def initialize_language(lang):
            conf = load_language_conf(lang)
            # ... set up language

        # Setup each class once
        class SomeManager(Manager):
            @once_per('cls')
            def _initialize_class(self, cls):
                pre_save.connect(self._pre_save, sender=cls)
                # ... set up signals, no dups


.. function:: raiser(exception_or_class=Exception, *args, **kwargs)

    Constructs function that raises given exception with given arguments on any invocation. You may pass a string instead of exception as a shortcut::

        mocker.patch('mod.Class.propname', property(raiser("Shouldn't be called")))

    This will raise an ``Exception`` with a corresponding message.


.. decorator:: reraise(errors, into)

    Intercepts any error of ``errors`` classes and reraises it as ``into`` error. Can be used as decorator or a context manager::

        with reraise(json.JSONDecodeError, SuspiciousOperation('Invalid JSON')):
            return json.loads(text)

    ``into`` can also be a callable to transform the error before reraising::

        @reraise(requests.RequestsError, lambda e: MyAPIError(error_desc(e)))
        def api_call(...):
            # ...


.. decorator:: retry(tries, errors=Exception, timeout=0, filter_errors=None)

    Every call of the decorated function is tried up to ``tries`` times. The first attempt counts as a try. Retries occur when any subclass of ``errors`` is raised, where``errors`` is an exception class or a list/tuple of exception classes. There will be a delay in ``timeout`` seconds between tries.

    A common use is to wrap some unreliable action::

        @retry(3, errors=HttpError)
        def download_image(url):
            # ... make http request
            return image

    Errors to retry may addtionally be filtered with ``filter_errors`` when classes are not specific enough::

        @retry(3, errors=HttpError, filter_errors=lambda e: e.status_code >= 500)
        def download_image(url):
            # ...

    You can pass a callable as ``timeout`` to achieve exponential delays or other complex behavior::

        @retry(3, errors=HttpError, timeout=lambda a: 2 ** a)
        def download_image(url):
            # ... make http request
            return image


.. function:: fallback(*approaches)

    Tries several approaches until one works. Each approach is either callable or a tuple ``(callable, errors)``, where errors is an exception class or a tuple of classes, which signal to fall back to next approach. If ``errors`` is not supplied then fall back is done for any :exc:`~py3:exceptions.Exception`::

        fallback(
            (partial(send_mail, ADMIN_EMAIL, message), SMTPException),
            partial(log.error, message),          # Handle any Exception
            (raiser(FeedbackError, "Failed"), ()) # Handle nothing
        )


.. function:: limit_error_rate(fails, timeout, exception=ErrorRateExceeded)

    If function fails to complete ``fails`` times in a row, calls to it will be intercepted for ``timeout`` with ``exception`` raised instead. A clean way to short-circuit function taking too long to fail::

        @limit_error_rate(fails=5, timeout=60,
                          exception=RequestError('Temporary unavailable'))
        def do_request(query):
            # ... make a http request
            return data

    Can be combined with :func:`ignore` to silently stop trying for a while::

        @ignore(ErrorRateExceeded, default={'id': None, 'name': 'Unknown'})
        @limit_error_rate(fails=5, timeout=60)
        def get_user(id):
            # ... make a http request
            return data


.. function:: throttle(period)

    Only runs a decorated function once in a ``period``::

        @throttle(60)
        def process_beat(pk, progress):
            Model.objects.filter(pk=pk).update(beat=timezone.now(), progress=progress)

        # Processing something, update progress info no more often then once a minute
        for i in ...:
            process_beat(pk, i / n)
            # ... do actual processing


.. decorator:: collecting

    Transforms generator or other iterator returning function into list returning one.

    Handy to prevent quirky iterator-returning properties::

        @property
        @collecting
        def path_up(self):
            node = self
            while node:
                yield node
                node = node.parent

    Also makes list constructing functions beautifully yielding.

    .. Or you could just write::

    ..     @property
    ..     def path_up(self):
    ..         going_up = iterate(attrgetter('parent'), self)
    ..         return list(takewhile(bool, going_up))


.. decorator:: joining(sep)

    Wraps common python idiom "collect then join" into a decorator. Transforms generator or alike into function, returning string of joined results. Automatically converts all elements to separator type for convenience.

    Goes well with generators with some ad-hoc logic within::

        @joining(', ')
        def car_desc(self):
            yield self.year_made
            if self.engine_volume: yield '%s cc' % self.engine_volume
            if self.transmission:  yield self.get_transmission_display()
            if self.gear:          yield self.get_gear_display()
            # ...

    Use ``bytes`` separator to get bytes result::

        @joining(b' ')
        def car_desc(self):
            yield self.year_made
            # ...

    See also :func:`str_join`.


.. decorator:: post_processing(func)

    Passes decorated function result through ``func``. This is the generalization of :func:`@collecting<collecting>` and :func:`@joining()<joining>`. Could save you writing a decorator or serve as an extended comprehension:

    ::

        @post_processing(dict)
        def make_cond(request):
            if request.GET['new']:
                yield 'year__gt', 2000
            for key, value in request.GET.items():
                if value == '':
                    continue
                # ...


.. decorator:: wrap_with(ctx)

    Turns a context manager into a decorator::

        @wrap_with(threading.Lock())
        def protected_func(...):
            # ...

.. raw:: html
    :file: descriptions.html