Conditions | 7 |
Total Lines | 60 |
Code Lines | 38 |
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 | import re |
||
95 | def test_doc(self): |
||
96 | """Test the doc maintaining the list of registered classes are correct.""" |
||
97 | |||
98 | filename = "docs/source/docs/registered_classes.md" |
||
99 | |||
100 | # generate dataframe |
||
101 | name_to_category = { |
||
102 | "Backbone": "backbone_class", |
||
103 | "Model": "model_class", |
||
104 | "Loss": "loss_class", |
||
105 | "Data Augmentation": "da_class", |
||
106 | "Data Loader": "data_loader_class", |
||
107 | "File Loader": "file_loader_class", |
||
108 | } |
||
109 | for category in KNOWN_CATEGORIES: |
||
110 | assert category in name_to_category.values() |
||
111 | |||
112 | df = dict(category=[], key=[], value=[]) |
||
113 | for (category, key), value in REGISTRY._dict.items(): |
||
114 | df["category"].append(category) |
||
115 | df["key"].append(f'"{key}"') |
||
116 | df["value"].append(f"`{value.__module__}.{value.__name__}`") |
||
117 | df = pd.DataFrame(df) |
||
118 | df = df.sort_values(["category", "key"]) |
||
119 | |||
120 | # generate lines |
||
121 | lines = ( |
||
122 | "# Registered Classes\n\n" |
||
123 | "> This file is generated automatically.\n\n" |
||
124 | "The following tables contain all registered classes " |
||
125 | "with their categories and keys." |
||
126 | ) |
||
127 | |||
128 | for category_name, category in name_to_category.items(): |
||
129 | df_cat = df[df.category == category] |
||
130 | lines += f"\n\n## {category_name}\n\n" |
||
131 | lines += ( |
||
132 | f"The category is `{category}`. " |
||
133 | f"Registered keys and values are as following.\n\n" |
||
134 | ) |
||
135 | lines += df_cat[["key", "value"]].to_markdown(index=False) |
||
136 | |||
137 | # check file content |
||
138 | with open(filename, "r") as f: |
||
139 | got = f.readlines() |
||
140 | got = "".join(got) |
||
141 | got = re.sub(r":-+", "", got) |
||
142 | got = got.replace(" ", "") |
||
143 | expected = re.sub(r":-+", "", lines) |
||
144 | expected = expected.replace(" ", "") |
||
145 | expected = expected + "\n" |
||
146 | |||
147 | assert got == expected |
||
148 | |||
149 | # rewrite the file |
||
150 | # if test failed, only need to temporarily comment out the assert |
||
151 | # then regenerate the file |
||
152 | if got != expected: |
||
153 | with open(filename, "w") as f: |
||
154 | f.writelines(lines) |
||
155 |