目录
参考链接:https://mmengine.readthedocs.io/zh_CN/latest/notes/code_style.html#id9
什么地方需要写注释
- 代码中技巧性的部分;
- 复杂操作前写上若干行;
- 不能一目了然的代码行尾添加注释;
下例展示了需要书写注释的情况:
1. 技巧性操作
# We use a weighted dictionary search to find out where i is in # the array. We extrapolate position based on the largest num # in the array and the array size and then do binary search to # get the exact number. if i & (i-1) == 0: # True if i is 0 or a power of 2.
2. 复杂操作,通过注释明确优先级关系
# self.build_func will be set with the following priority: # 1. build_func # 2. parent.build_func # 3. build_from_cfg if build_func is None: if parent is not None: self.build_func = parent.build_func else: self.build_func = build_from_cfg else: self.build_func = build_func
3. 不能一目了然,通过注释帮助他人了解背景
def _save_ckpt(checkpoint, file): # The 1.6 release of PyTorch switched torch.save to use a new # zipfile-based file format. It will cause RuntimeError when a # checkpoint was saved in high version (PyTorch version>=1.6.0) but # loaded in low version (PyTorch version<1.6.0). More details at # https://github.com/open-mmlab/mmpose/issues/904 if digit_version(TORCH_VERSION) >= digit_version('1.6.0'): torch.save(checkpoint, file, _use_new_zipfile_serialization=False) else: torch.save(checkpoint, file)
注释的格式是什么
- 注释至少离开代码2个空格;
- 可以使用 Markdown 语法;
下例展示了使用 Markdown 语法的注释:
# `_reversed_padding_repeated_twice` is the padding to be passed to # `F.pad` if needed (e.g., for non-zero padding types that are # implemented as two ops: padding + conv). `F.pad` accepts paddings in # reverse order than the dimension. self._reversed_padding_repeated_twice = _reverse_repeat_tuple(self.padding, 2)
注意事项
- 不要描述代码;
下例展示了一种错误的无效的这是书写方式:
# Wrong: # Now go through the b array and make sure whenever i occurs # the next element is i+1 # Wrong: if i & (i-1) == 0: # True if i bitwise and i-1 is 0.