一、Docstring format

1、方法参数注释

File -> Settings -> Tools -> Python Integrated Tools -> Docstrings -> Docstring format

有5中风格,Plain、Epytext、reStructuredText、Numpy、Google。
image.png
在方法名下方输入三个双(单)引号,回车,自动生成;五种格式如下:

  1. def docstrings_func_plain(parm_a, parm_b, parm_c):
  2. """
  3. Plain 风格
  4. """
  5. def docstrings_func_epytext(parm_a, parm_b, parm_c):
  6. """
  7. Epytext 风格
  8. @param parm_a: 参数a
  9. @param parm_b: 参数b
  10. @param parm_c: 参数c
  11. @return: 结果a
  12. """
  13. def docstrings_func_restructuredtext(parm_a, parm_b, parm_c):
  14. """
  15. reStructuredText 风格
  16. :param parm_a: 参数a
  17. :param parm_b: 参数b
  18. :param parm_c: 参数c
  19. :return: 结果a
  20. """
  21. def docstrings_func_numpy(parm_a, parm_b, parm_c):
  22. """
  23. NumPy 风格
  24. Parameters
  25. ----------
  26. parm_a : 参数a
  27. parm_b : 参数b
  28. parm_c : 参数a
  29. Returns
  30. -------
  31. result_a : 结果a
  32. """
  33. def docstrings_func_google(parm_a, parm_b, parm_c):
  34. """
  35. Google 风格
  36. Args:
  37. parm_a: 参数a
  38. parm_b: 参数b
  39. parm_c: 参数c
  40. Returns:
  41. result_a 结果a
  42. """

2、参数类型设置

Python是动态语言,使用动态类型(Dynamic Typed),即在运行时确定数据类型,变量使用之前不需要类型声明;对于一些已经确定类型的参数,加上类型的注释,可以借助pyCharm的方法类型检查功能,在书写代码时就能够提前发现错误。

File -> Settings -> Editor -> General -> Smart Keys -> Insert type placeholders in the documentation comment stub

image.png

二、File and Code Templates

File -> Setting -> Editor -> File and Code Templates

  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. """
  4. Version : 0.1
  5. Author : yx
  6. Date : ${YEAR}-${MONTH}-${DAY}
  7. """

image.png
Live Templates

File -> Setting -> Editor -> Live Templates

  1. # -*- coding: utf-8 -*-

image.png

三、Type Hints

  1. def fun(x):
  2. x.??? #can't hint or check

写函数的时候, 编译器并不知道形参x的类型, 所以函数体中调用x的字段与方法时, IDE 既不能作提示, 也不能作检查, 让人很捉急.
这是动态语言的通病. 所以很多人更喜欢java, c++.

但各种语言都是与时俱进的, javascript 有了 超集 TypeScript. 那么 python3 也在语言级别加入了 type hint. Provide a standard way of annotating a function’s parameters and return values.

python 仍是一门 动态语言, 所以这个注解加不加都可以.

1、函数签名

  1. # 指定参数的类型, 函数的返回类型, 以及局部变量的类型
  2. def foo(a: str, b: str) -> str:
  3. return 'hi'

2、普通变量 及 类的成员字段

  1. # 指定参数的类型, 函数的返回类型, 以及局部变量的类型
  2. x = None # type: str
  3. x= '' # 其实IDE已经能知道是str类型了
  4. x:str=None #跟函数形参的hint类似, 以 ":+type" 构成

py2写法: 只能用 注释, 不能用 :type 表示

3、集合泛型

  1. my_list:List[Student]=[] # py3
  2. # py2
  3. my_dict={} # type: Dict[int,str]
  4. my_list_2=None # type: Tuple[int,Tuple[int]]

typeHint必须使用typing 包下相应的类.
image.png

对于层级较深的类, 需要注意相应的 import 路径, 会直接影响 IDE 的解析

  1. import matplotlib
  2. # 此时 IDE 无法定位到 axes, 因为它会去 matplotlib/__init__.py 中找 axes
  3. x = x # type: matplotlib.axes.Axes
  4. import matplotlib.axes
  5. # 此时 IDE 才能正确定位, 因为它会去 matplotlib/axes/__init__.py 中找 Axes
  6. x = x # type: matplotlib.axes.Axes