| Conditions | 6 |
| Total Lines | 56 |
| Code Lines | 23 |
| Lines | 0 |
| Ratio | 0 % |
| Changes | 0 | ||
Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.
For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.
Commonly applied refactorings include:
If many parameters/temporary variables are present:
| 1 | """Control function definition.""" |
||
| 10 | def sequence(children: List[CallableFunction], succes_threshold: Optional[int] = None) -> AsyncInnerFunction: |
||
| 11 | """Return a function which execute children in sequence. |
||
| 12 | |||
| 13 | succes_threshold parameter generalize traditional sequence/fallback and |
||
| 14 | must be in [0, len(children)]. Default value is (-1) means len(children) |
||
| 15 | |||
| 16 | if #success = succes_threshold, return a success |
||
| 17 | |||
| 18 | if #failure = len(children) - succes_threshold, return a failure |
||
| 19 | |||
| 20 | What we can return as value and keep sematic Failure/Success: |
||
| 21 | - an array of previous result when success |
||
| 22 | - last failure when fail |
||
| 23 | |||
| 24 | Args: |
||
| 25 | children (List[CallableFunction]): list of Awaitable |
||
| 26 | succes_threshold (int): succes threshold value |
||
| 27 | |||
| 28 | Returns: |
||
| 29 | (AsyncInnerFunction): an awaitable function. |
||
| 30 | |||
| 31 | Raises: |
||
| 32 | (AssertionError): if succes_threshold is invalid |
||
| 33 | """ |
||
| 34 | _succes_threshold = succes_threshold or len(children) |
||
| 35 | if not (0 <= _succes_threshold <= len(children)): |
||
| 36 | raise AssertionError('succes_threshold') |
||
| 37 | |||
| 38 | failure_threshold = len(children) - _succes_threshold + 1 |
||
| 39 | |||
| 40 | _children = [to_async(child) for child in children] |
||
| 41 | |||
| 42 | @node_metadata(properties=['_succes_threshold']) |
||
| 43 | async def _sequence(): |
||
| 44 | success = 0 |
||
| 45 | failure = 0 |
||
| 46 | results = [] |
||
| 47 | |||
| 48 | for child in _children: |
||
| 49 | last_result = await child() |
||
| 50 | results.append(last_result) |
||
| 51 | |||
| 52 | if bool(last_result): |
||
| 53 | success += 1 |
||
| 54 | if success == _succes_threshold: |
||
| 55 | # last evaluation is a success |
||
| 56 | return results |
||
| 57 | else: |
||
| 58 | failure += 1 |
||
| 59 | if failure == failure_threshold: |
||
| 60 | # last evaluation is a failure |
||
| 61 | return last_result |
||
| 62 | # should be never reached |
||
| 63 | return FAILURE |
||
| 64 | |||
| 65 | return _sequence |
||
| 66 | |||
| 148 |