python之PEP注释规范范例

本是古典 何须时尚 2022-12-28 04:04 309阅读 0赞

目录

  • 1.Class说明规范
  • 2.函数说明范例
  • 3.py文件说明范例
  • 4.引用包的注释范例
  • 5.package说明规范

1.Class说明规范

Class说明,对于传入的参数,属于parameters, Attributes是指的class的属性,对于传入的参数一般是为了初始化类的实例的属性,而atrributes是指的根据传入的参数,创建的新的属性,这些属性没有在parameters中出现. method表示类中的方法。

  1. class PreparedConstraint(object):
  2. """Constraint prepared from a user defined constraint. On creation it will check whether a constraint definition is valid and the initial point is feasible. If created successfully, it will contain the attributes listed below. Parameters ---------- constraint : {NonlinearConstraint, LinearConstraint`, Bounds} Constraint to check and prepare. x0 : array_like Initial vector of independent variables. sparse_jacobian : bool or None, optional If bool, then the Jacobian of the constraint will be converted to the corresponded format if necessary. If None (default), such conversion is not made. finite_diff_bounds : 2-tuple, optional Lower and upper bounds on the independent variables for the finite difference approximation, if applicable. Defaults to no bounds. Attributes ---------- fun : {VectorFunction, LinearVectorFunction, IdentityVectorFunction} Function defining the constraint wrapped by one of the convenience classes. bounds : 2-tuple Contains lower and upper bounds for the constraints --- lb and ub. These are converted to ndarray and have a size equal to the number of the constraints. keep_feasible : ndarray Array indicating which components must be kept feasible with a size equal to the number of the constraints. Methods ------- solve Returns J^-1 * v update Updates Jacobian to point `x` (where the function has residual `Fx`) matvec : optional Returns J * v rmatvec : optional Returns A^H * v Notes ----- There may be additional attributes not listed above depending of the specific solver. Since this class is essentially a subclass of dict with attribute accessors, one can see which attributes are available using the `keys()` method. """

2.函数说明范例

对于编写的接口函数必须要有说明,对于一些不开放的函数也尽量写说明(一些工具函数以及不是很重要或简单的函数可以没有函数说明)。函数说明主要包括以下几个部分(有序):函数概述、Parameters、Returns、See also 、Notes、References、Examples。 每个部分都以“—————”开始,在这行符号的下面开始正式说明每个部分,每个部分结束后以回车隔开,然后接着写下一个部分。See also是指的其他地方与之关联的模块,可有可无。References表示引用,该部分的实现参考文献。Examples部分写出如何调用,尽量写范例展示调用以及结果的整个过程。

  1. def __init__(self, spacing, height, SNR, x_min, x_max, y_min, y_max,
  2. collection_direction):
  3. """Minimization of scalar function of one or more variables. Parameters ---------- fun : callable The objective function to be minimized. ``fun(x, *args) -> float`` where ``x`` is an 1-D array with shape (n,) and ``args`` is a tuple of the fixed parameters needed to completely specify the function. x0 : ndarray, shape (n,) Initial guess. Array of real elements of size (n,), where 'n' is the number of independent variables. Returns ------- res : OptimizeResult The optimization result represented as a ``OptimizeResult`` object. Important attributes are: ``x`` the solution array, ``success`` a Boolean flag indicating if the optimizer exited successfully and ``message`` which describes the cause of the termination. See `OptimizeResult` for a description of other attributes. See also -------- minimize_scalar : Interface to minimization algorithms for scalar univariate functions show_options : Additional options accepted by the solvers Notes ----- This section describes the available solvers that can be selected by the 'method' parameter. The default method is *BFGS*. **Unconstrained minimization** Method :ref:`Nelder-Mead <optimize.minimize-neldermead>` uses the Simplex algorithm [1]_, [2]_. This algorithm is robust in many applications. However, if numerical computation of derivative can be trusted, other algorithms using the first and/or second derivatives. **Bound-Constrained minimization** 。。。。 References ---------- .. [1] Nelder, J A, and R Mead. 1965. A Simplex Method for Function Minimization. The Computer Journal 7: 308-13. .. [2] Wright M H. 1996. Direct search methods: Once scorned, now respectable, in Numerical Analysis 1995: Proceedings of the 1995 Dundee Biennial Conference in Numerical Analysis (Eds. D F Griffiths and G A Watson). Addison Wesley Longman, Harlow, UK. 191-208. Examples -------- Let us consider the problem of minimizing the Rosenbrock function. This function (and its respective derivatives) is implemented in `rosen` (resp. `rosen_der`, `rosen_hess`) in the `scipy.optimize`. >>> from scipy.optimize import minimize, rosen, rosen_der A simple application of the *Nelder-Mead* method is: >>> x0 = [1.3, 0.7, 0.8, 1.9, 1.2] >>> res = minimize(rosen, x0, method='Nelder-Mead', tol=1e-6) >>> res.x array([ 1., 1., 1., 1., 1.]) """

3.py文件说明范例

每个.py文件注意最开头要有说明,先简单介绍下该文件的作用,然后指出该文件中开放的函数,然后通过__all__把开放的函数放进去,以便于通过import *这种方式导入包的时候,可以全部将开放的接口导入,而避免非开放的接口导入。对于每个文件的说明,可以通过导入该文件,然后通过__doc__查看该模块的说明。

  1. """ Unified interfaces to minimization algorithms. Functions --------- - minimize : minimization of a function of several variables. - minimize_scalar : minimization of a function of one variable. """
  2. __all__ = ['minimize', 'minimize_scalar']

4.引用包的注释范例

对于需要比较多的引用,注意把引用的给进行分类,按照应用模块进行说明下

  1. # unconstrained minimization
  2. from ._trustregion_dogleg import _minimize_dogleg
  3. from ._trustregion_ncg import _minimize_trust_ncg
  4. from ._trustregion_krylov import _minimize_trust_krylov
  5. # constrained minimization
  6. from .lbfgsb import _minimize_lbfgsb
  7. from .tnc import _minimize_tnc

5.package说明规范

package的说明主要注释在__init__.py文件的开头,对于主包,首先写明包名,以”=====”与下面的内容进行分隔。然后是Provides,指明该包支持的内容。接着是How to use the documentation,指明如何查看说明文档。Available subpackages指明该包下可利用的子包有哪些。Utilities指明包的一些工具或基础内容:如配置、测试、版本等信息。Viewing documentation using Ipython信息可有可无,对于咱们这个平台如果包发布了的话,可以写明,没发布的话就不用写这部分了。子包的内容和这个类似,给这些包添加说明的时候,一定要把这个包解释清楚,可以在注释里面添加除了上面提到这些模块以外的内容。

  1. """
  2. NumPy
  3. =====
  4. Provides
  5. 1. An array object of arbitrary homogeneous items
  6. 2. Fast mathematical operations over arrays
  7. 3. Linear Algebra, Fourier Transforms, Random Number Generation
  8. How to use the documentation
  9. ----------------------------
  10. Documentation is available in two forms: docstrings provided
  11. with the code, and a loose standing reference guide, available from
  12. `the NumPy homepage <https://www.scipy.org>`_.
  13. Available subpackages
  14. ---------------------
  15. doc
  16. Topical documentation on broadcasting, indexing, etc.
  17. lib
  18. Basic functions used by several sub-packages.
  19. Utilities
  20. ---------
  21. test
  22. Run numpy unittests
  23. show_config
  24. Show numpy build configuration
  25. __version__
  26. NumPy version string
  27. Viewing documentation using IPython
  28. -----------------------------------
  29. Start IPython with the NumPy profile (``ipython -p numpy``),

其他注意点:

1.说明尽量以一句话概述,换行再加以具体解释说明,对于重要的注释,以双行等号突出说明:
2.对于上面提到的关于注释的很多部分都是共用的,比如reference、notes可以用在函数说明中,也可以用在class说明规范里面,注意灵活使用。
3.行注释:至少使用两个空格和语句分开,注意不要使用无意义的注释

参考:https://github.com/scipy/scipy/blob/master/scipy/optimize/optimize.py

发表评论

表情:
评论列表 (有 0 条评论,309人围观)

还没有评论,来说两句吧...

相关阅读

    相关 python编码规范PEP8总结

    关于这篇文章,建议快速浏览,记住一些关键点即可,更多的实际编程中把这些关键点应用到自己的编写过程中。 目录 小括号,中括号以及大括号中的隐式续行方式

    相关 PEP8 Python 编码规范整理

    决定开始Python之路了,利用业余时间,争取更深入学习Python。编程语言不是艺术,而是工作或者说是工具,所以整理并遵循一套编码规范是十分必要的。所以今天下午我根据PEP