| Conditions | 3 |
| Total Lines | 78 |
| Code Lines | 52 |
| 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 | from collections import namedtuple |
||
| 13 | def rx_collector(initial_value: T) -> Collector: |
||
| 14 | """Create an observer collector. |
||
| 15 | |||
| 16 | Args: |
||
| 17 | initial_value (T): initial value which determin result type (list, dict, base type) |
||
| 18 | |||
| 19 | Returns: |
||
| 20 | (Collector[T]): a collector instance |
||
| 21 | |||
| 22 | """ |
||
| 23 | |||
| 24 | _is_finish = False |
||
| 25 | _has_error = False |
||
| 26 | _error = None |
||
| 27 | |||
| 28 | if isinstance(initial_value, dict): |
||
| 29 | _dict = dict(initial_value) |
||
| 30 | |||
| 31 | async def _on_next(item: Any): |
||
| 32 | nonlocal _dict |
||
|
|
|||
| 33 | (k, v) = item |
||
| 34 | _dict[k] = v |
||
| 35 | |||
| 36 | def _get_result() -> Any: |
||
| 37 | nonlocal _dict |
||
| 38 | return _dict |
||
| 39 | |||
| 40 | elif isinstance(initial_value, list): |
||
| 41 | _list = list(initial_value) |
||
| 42 | |||
| 43 | async def _on_next(item: Any): |
||
| 44 | nonlocal _list |
||
| 45 | _list.append(item) |
||
| 46 | |||
| 47 | def _get_result() -> Any: |
||
| 48 | nonlocal _list |
||
| 49 | return _list |
||
| 50 | |||
| 51 | else: |
||
| 52 | _value = initial_value |
||
| 53 | |||
| 54 | async def _on_next(item: Any): |
||
| 55 | nonlocal _value |
||
| 56 | _value = item |
||
| 57 | |||
| 58 | def _get_result() -> Any: |
||
| 59 | nonlocal _value |
||
| 60 | return _value |
||
| 61 | |||
| 62 | async def _on_completed(): |
||
| 63 | nonlocal _is_finish |
||
| 64 | _is_finish = True |
||
| 65 | |||
| 66 | async def _on_error(err: Any): |
||
| 67 | nonlocal _has_error, _error |
||
| 68 | _error = err |
||
| 69 | _has_error = True |
||
| 70 | |||
| 71 | def _get_is_finish(): |
||
| 72 | nonlocal _is_finish |
||
| 73 | return _is_finish |
||
| 74 | |||
| 75 | def _get_has_error(): |
||
| 76 | nonlocal _has_error |
||
| 77 | return _has_error |
||
| 78 | |||
| 79 | def _get_error(): |
||
| 80 | nonlocal _error |
||
| 81 | return _error |
||
| 82 | |||
| 83 | return CollectorDefinition( |
||
| 84 | on_next=_on_next, |
||
| 85 | on_error=_on_error, |
||
| 86 | on_completed=_on_completed, |
||
| 87 | result=_get_result, |
||
| 88 | is_finish=_get_is_finish, |
||
| 89 | has_error=_get_has_error, |
||
| 90 | error=_get_error, |
||
| 91 | ) |
||
| 92 |