| Conditions | 12 |
| Total Lines | 51 |
| Lines | 0 |
| Ratio | 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:
Complex classes like DocumentationComment.from_docstring() often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
| 1 | import inspect |
||
| 24 | @classmethod |
||
| 25 | def from_docstring(cls, docstring): |
||
| 26 | """ |
||
| 27 | Parses a python docstring. Usable attributes are: |
||
| 28 | :param |
||
| 29 | @param |
||
| 30 | :return |
||
| 31 | @return |
||
| 32 | """ |
||
| 33 | lines = inspect.cleandoc(docstring).split("\n") |
||
| 34 | |||
| 35 | parse_mode = cls._ParseMode.DESCRIPTION |
||
| 36 | cur_param = "" |
||
| 37 | |||
| 38 | desc = "" |
||
| 39 | param_dict = OrderedDict() |
||
| 40 | retval_desc = "" |
||
| 41 | for line in lines: |
||
| 42 | line = line.strip() |
||
| 43 | |||
| 44 | if line.startswith(":param ") or line.startswith("@param "): |
||
| 45 | parse_mode = cls._ParseMode.PARAM |
||
| 46 | splitted = line[7:].split(":", 1) |
||
| 47 | cur_param = splitted[0] |
||
| 48 | param_dict[cur_param] = splitted[1].strip() |
||
| 49 | |||
| 50 | continue |
||
| 51 | |||
| 52 | if line.startswith(":return: ") or line.startswith("@return: "): |
||
| 53 | parse_mode = cls._ParseMode.RETVAL |
||
| 54 | retval_desc = line[9:].strip() |
||
| 55 | |||
| 56 | continue |
||
| 57 | |||
| 58 | def concat_doc_parts(old: str, new: str): |
||
| 59 | if new != '' and not old.endswith('\n'): |
||
| 60 | return old + ' ' + new |
||
| 61 | |||
| 62 | return old + (new if new != '' else '\n') |
||
| 63 | |||
| 64 | if parse_mode == cls._ParseMode.RETVAL: |
||
| 65 | retval_desc = concat_doc_parts(retval_desc, line) |
||
| 66 | elif parse_mode == cls._ParseMode.PARAM: |
||
| 67 | param_dict[cur_param] = concat_doc_parts(param_dict[cur_param], |
||
| 68 | line) |
||
| 69 | else: |
||
| 70 | desc = concat_doc_parts(desc, line) |
||
| 71 | |||
| 72 | return (cls(desc=desc.strip(), |
||
| 73 | param_dict=param_dict, |
||
| 74 | retval_desc=retval_desc.strip())) |
||
| 75 | |||
| 78 |