Plone技术资料

 找回密码
 立即注册
搜索
热搜: 活动 交友 discuz
查看: 1043|回复: 0

Python 源码样式指导及辅助工具

[复制链接]
发表于 2019-7-19 09:37:23 | 显示全部楼层 |阅读模式
Python styleguideIntroduction
We’ve modeled the following rules and recommendations based on the following documents:

Line length
All Python code in this package should be PEP8 valid. This includes adhering to the 80-char line length. If you absolutely need to break this rule, append `` # noqa: E501`` to the offending line to skip it in syntax checks.
Configuring your editor to display a line at 79th column helps a lot here and saves time.

The line length rule also applies to non-python source files, such as .zcml files, but is a bit more relaxed there.

The rule explicitly does not apply to documentation .rst files. For .rst files including the package documentation but also README.rst, CHANGES.rst and doctests, use semantic line-breaks and add a line break after each sentence. See the :doc:` documentation styleguide </about/contributing/documentation_styleguide>` for the reasoning behind it.

Breaking lines
Based on code we love to look at (Pyramid, Requests, etc.), we allow the following two styles for breaking long lines into blocks:
  • Break into next line with one additional indent block.
    1. foo = do_something(
    2.     very_long_argument='foo',
    3.     another_very_long_argument='bar',
    4. )

    5. # For functions the ): needs to be placed on the following line
    6. def some_func(
    7.     very_long_argument='foo',
    8.     another_very_long_argument='bar',
    9. ):
    复制代码

  • If this still doesn’t fit the 80-char limit, break into multiple lines.
    1. foo = dict(
    2.     very_long_argument='foo',
    3.     another_very_long_argument='bar',
    4. )

    5. a_long_list = [
    6.     "a_fairly_long_string",
    7.     "quite_a_long_string_indeed",
    8.     "an_exceptionally_long_string_of_characters",
    9. ]
    复制代码

  • Arguments on first line, directly after the opening parenthesis are forbidden when breaking lines.
  • The last argument line needs to have a trailing comma (to be nice to the next developer coming in to add something as an argument and minimize VCS diffs in these cases).
  • The closing parenthesis or bracket needs to have the same indentation level as the first line.
  • Each line can only contain a single argument.
  • The same style applies to dicts, lists, return calls, etc.

autopep8
Making old code pep8 compliant can be a lot of work. There is a tool that can automatically do some of this work for you: autopep8. This fixes various issues, for example fixing indentation to be a multiple of four. Just install it with pip and call it like this:
  1. pip install autopep8
  2. autopep8 -i filename.py
  3. autopep8 -i -r directory
复制代码


It is best to first run autopep8 in the default non aggressive mode, which means it only does whitespace changes. To run this recursively on the current directory, changing files in place:
  1. autopep8 <font color="rgb(102, 102, 102)">-</font>i <font color="rgb(102, 102, 102)">-</font>r <font color="rgb(102, 102, 102)">.</font>
复制代码


Quickly check the changes and then commit them.
WARNING: be very careful when running this in a skins directory, if you run it there at all. It will make changes to the top of the file like this, which completely breaks the skin script:
  1. -##parameters=policy_in=''
  2. +# parameters=policy_in=''
复制代码


With those safe changes out of the way, you can move on to a second, more aggresive round:
  1. autopep8 <font color="rgb(102, 102, 102)">-</font>i <font color="rgb(102, 102, 102)">--</font>aggressive <font color="rgb(102, 102, 102)">-</font>r <font color="rgb(102, 102, 102)">.</font>
复制代码


Check these changes more thoroughly. At the very least check if Plone can still start in the foreground and that there are no failures or errors in the tests.
Not all changes are always safe. You can ignore some checks:
  1. autopep8 <font color="rgb(102, 102, 102)">-</font>i <font color="rgb(102, 102, 102)">--</font>ignore W690,E711,E721 <font color="rgb(102, 102, 102)">--</font>aggressive <font color="rgb(102, 102, 102)">-</font>r <font color="rgb(102, 102, 102)">.</font>
复制代码


This skips the following changes:
  • W690: Fix various deprecated code (via lib2to3). (Can be bad for Python 2.4.)
  • E721: Use isinstance() instead of comparing types directly. (There are uses of this in for example GenericSetup and plone.api that must not be fixed.)
  • E711: Fix comparison with None. (This can break SQLAlchemy code.)
You can check what would be changed by one specific code:
  1. autopep8 <font color="rgb(102, 102, 102)">--</font>diff <font color="rgb(102, 102, 102)">--</font>select E309 <font color="rgb(102, 102, 102)">-</font>r <font color="rgb(102, 102, 102)">.</font>
复制代码




Indentation
For Python files, we stick with the PEP 8 recommondation: Use 4 spaces per indentation level.
For ZCML and XML (GenericSetup) files, we recommend the Zope Toolkit’s coding style on ZCML:
Indentation of 2 characters to show nesting, 4 characters to list attributes on separate lines.This distinction makes it easier to see the difference between attributes and nested elements.


Quoting
For strings and such prefer using single quotes over double quotes. The reason is that sometimes you do need to write a bit of HTML in your python code, and HTML feels more natural with double quotes so you wrap HTML string into single quotes. And if you are using single quotes for this reason, then be consistent and use them everywhere.
There are two exceptions to this rule:
  • docstrings should always use double quotes (as per PEP-257).
  • if you want to use single quotes in your string, double quotes might make more sense so you don’t have to escape those single quotes.
    1. # GOOD
    2. print 'short'
    3. print 'A longer string, but still using single quotes.'

    4. # BAD
    5. print "short"
    6. print "A long string."

    7. # EXCEPTIONS
    8. print "I want to use a 'single quote' in my string."
    9. """This is a docstring."""
    复制代码


Docstrings style
Read and follow http://www.python.org/dev/peps/pep-0257/. There is one exception though: We reject BDFL’s recommendation about inserting a blank line between the last paragraph in a multi-line docstring and its closing quotes as it’s Emacs specific and two Emacs users here on the Beer & Wine Sprint both support our way.
The content of the docstring must be written in the active first-person form, e.g. “Calculate X from Y” or “Determine the exact foo of bar”.
  1. def foo():
  2.     """Single line docstring."""

  3. def bar():
  4.     """Multi-line docstring.

  5.     With the additional lines indented with the beginning quote and a
  6.     newline preceding the ending quote.
  7.     """
复制代码


If you wanna be extra nice, you are encouraged to document your method’s parameters and their return values in a reST field list syntax.
  1. :param foo: blah blah
  2. :type foo: string
  3. :param bar: blah blah
  4. :type bar: int
  5. :returns: something
复制代码


Check out the plone.api source for more usage examples. Also, see the following for examples on how to write good Sphinxy docstrings: http://stackoverflow.com/questions/4547849/good-examples-of-python-docstrings-for-sphinx.

Unit tests style
Read http://www.voidspace.org.uk/python/articles/unittest2.shtml to learn what is new in unittest2 and use it.
This is not true for in-line documentation tests. Those still use old unittest test-cases, so you cannot use assertIn and similar.

String formatting
As per http://docs.python.org/2/library/stdtypes.html#str.format, we should prefer the new style string formatting (.format()) over the old one (% ()).
Also use numbering or keyword arguments, like so:
  1. # GOOD
  2. print "{0} is not {1}".format(1, 2)
  3. print "{bar} is not {foo}".format(foo=1, bar=2)
复制代码


and not like this:
  1. # BAD
  2. print "{} is not {}".format(1, 2)
  3. print "%s is not %s" % (1, 2)
复制代码


because Python 2.6 supports only explicitly numbered placeholders.

About imports
  • Don’t use * to import everything from a module, because if you do, pyflakes cannot detect undefined names (W404).
  • Don’t use commas to import multiple things on a single line. Some developers use IDEs (like Eclipse) or tools (such as mr.igor) that expect one import per line. Let’s be nice to them.
  • Don’t use relative paths, again to be nice to people using certain IDEs and tools. Also Google Python Style Guide recommends against it.
    1. # GOOD
    2. from plone.app.testing import something
    3. from zope.component import getMultiAdapter
    4. from zope.component import getSiteManager
    复制代码


    instead of
    1. # BAD
    2. from plone.app.testing import *
    3. from zope.component import getMultiAdapter, getSiteManager
    复制代码

  • Don’t catch ImportError to detect whether a package is available or not, as it might hide circular import errors. Instead, use pkg_resources.get_distribution and catch DistributionNotFound. More background at http://do3.cc/blog/2010/08/20/do-not-catch-import-errors,-use-pkg_resources/.
    1. # GOOD
    2. import pkg_resources

    3. try:
    4.     pkg_resources.get_distribution('plone.dexterity')
    5. except pkg_resources.DistributionNotFound:
    6.     HAS_DEXTERITY = False
    7. else:
    8.     HAS_DEXTERITY = True
    复制代码

    instead of
    1. # BAD
    2. try:
    3.     import plone.dexterity
    4.     HAVE_DEXTERITY = True
    5. except ImportError:
    6.     HAVE_DEXTERITY = False
    复制代码

Grouping and sorting
Since Plone has such a huge code base, we don’t want to lose developer time figuring out into which group some import goes (standard lib?, external package?, etc.). We sort everything alphabetically case insensitive and insert one blank line between fromfoo import bar and import baz blocks. Conditional imports come last. Don’t use multi-line imports but import each identifier from a module in a separate line. Again, we do not distinguish between what is standard lib, external package or internal package in order to save time and avoid the hassle of explaining which is which.
  1. # GOOD
  2. from __future__ import division
  3. from Acquisition import aq_inner
  4. from datetime import datetime
  5. from datetime import timedelta
  6. from plone.api import portal
  7. from plone.api.exc import MissingParameterError
  8. from Products.CMFCore.interfaces import ISiteRoot
  9. from Products.CMFCore.WorkflowCore import WorkflowException

  10. import pkg_resources
  11. import random

  12. try:
  13.     pkg_resources.get_distribution('plone.dexterity')
  14. except pkg_resources.DistributionNotFound:
  15.     HAS_DEXTERITY = False
  16. else:
  17.     HAS_DEXTERITY = True
复制代码


isort, a python tool to sort imports can be configured to sort exactly as described above.
Add the following:
  1. [settings]
  2. force_alphabetical_sort = True
  3. force_single_line = True
  4. lines_after_imports = 2
  5. line_length = 200
  6. not_skip = __init__.py
复制代码


To either .isort.cfg or changing the header from [settings] to [isort] and putting it on setup.cfg.
You can also use plone.recipe.codeanalysis with the flake8-isort plugin enabled to check for it.


Declaring dependencies
All direct dependencies should be declared in install_requires or extras_require sections in setup.py. Dependencies, which are not needed for a production environment (like “develop” or “test” dependencies) or are optional (like “Archetypes” or “Dexterity” flavors of the same package) should go in extras_require. Remember to document how to enable specific features (and think of using zcml:condition statements, if you have such optional features).
Generally all direct dependencies (packages directly imported or used in ZCML) should be declared, even if they would already be pulled in by other dependencies. This explicitness reduces possible runtime errors and gives a good overview on the complexity of a package.
For example, if you depend on Products.CMFPlone and use getToolByName from Products.CMFCore, you should also declare the CMFCore dependency explicitly, even though it’s pulled in by Plone itself. If you use namespace packages from the Zope distribution like Products.Five you should explicitly declare Zope as dependency.
Inside each group of dependencies, lines should be sorted alphabetically.

Versioning scheme
For software versions, use a sequence-based versioning scheme, which is compatible with setuptools:
  1. MAJOR.MINOR[.MICRO][.STATUS]
复制代码


The way, setuptools interprets versions is intuitive:
  1. 1.0 < 1.1.dev < 1.1.a1 < 1.1.a2 < 1.1.b < 1.1.rc1 < 1.1 < 1.1.1
复制代码


You can test it with setuptools:
  1. >>> from pkg_resources import parse_version
  2. >>> parse_version('1.0') < parse_version('1.1.dev')
  3. ... < parse_version('1.1.a1') < parse_version('1.1.a2')
  4. ... < parse_version('1.1.b') < parse_version('1.1.rc1')
  5. ... < parse_version('1.1') < parse_version('1.1.1')
  6. True
复制代码


dev and dev0 are treated as the same:
  1. >>> parse_version('1.1.dev') == parse_version('1.1.dev0')
  2. True
复制代码


Setuptools recommends to separate parts with a dot. The website about semantic versioning is also worth a read.

Concrete Rules
  • Do not use tabs in Python code! Use spaces as indenting, 4 spaces for each level. We don’t “require” PEP8, but most people use it and it’s good for you.
  • Indent properly, even in HTML.
  • Never use a bare except. Anything like except: pass will likely be reverted instantly.
  • Avoid taln-error, since this swallows exceptions.
  • Don’t use hasattr() - this swallows exceptions, use getattr(foo, 'bar', None) instead. The problem with swallowed exceptions is not just poor error reporting. This can also mask ConflictErrors, which indicate that something has gone wrong at the ZODB level!
  • Never put any HTML in Python code and return it as a string. There are exceptions, though.
  • Do not acquire anything unless absolutely necessary, especially tools. For example, instead of using context.plone_utils, use:
    1. from Products.CMFCore.utils import getToolByName
    2. plone_utils = getToolByName(context, 'plone_utils')
    复制代码

  • Do not put too much logic in ZPT (use Views instead!)
  • Remember to add i18n tags in ZPTs and Python code.



回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|小黑屋|Archiver|手机版|Plone技术资料 ( 湘ICP备14006519号-1 )

GMT+8, 2019-8-23 12:32 , Processed in 0.049518 second(s), 14 queries , Gzip On.

Powered by Plone! X3.4

© 2001-2019 Plone.org.

快速回复 返回顶部 返回列表