python代碼風格建議

來源:互聯網
上載者:User
   python 以其結構嚴格著稱,同時也以其命名規範散漫出名,算亂無規矩的命名尤其給開發人員帶來理解上的誤區。

尤其像python、ruby動態語言,由於在運行期隨時可能出現方法或者屬性的增減,規則的命名尤其重要。 ruby語言本身定義的文法規則較為隨意,但卻不乏一一對應的隱含規則,使人一目瞭然。其命名規則甚至滲透進了語言本身的規範當中在命名規則這一點上python顯得沒規沒距。需要逐步養成一個好的編碼命名規範。 本文從各大網站文章中搜集了一些代碼風格,命名規範。便於學習參考。  代碼風格: 
  1. 使用空格來表示縮排,而不要使用定位字元tab,請勿將兩者混用
  2. 函數間換行至少一行
  3. 類之間換行至少兩行
  4. dict、list、tuple、參數列表時,應該在逗號,前添加一個空格
  5. dict中key之後的冒號:應在value與冒號:之間添加空格,而不是:與key之前間
  6. 較長代碼(大於79chars)使用反斜線\換行。換行後新行的起始處應該與前一個分隔字元對齊(是參數換行則與左括弧(對齊
  7. import位於module comments 與 docstring 之後,常量聲明之前
  8. 3.0一下版本的代碼檔案建議以latin字元編碼。3.0以上則推薦utf-8
  9. 代碼中有操作符運算,請注意優先順序,優先的操作緊縮,或者加括弧
  10. 等號左右兩邊請勿加空格
  11. 盡量不要將多行代碼放在同一行
  12. 少使用inline comments(行後注釋)
  13. block comments (用#開頭的多行函數注釋),保持與目標函數 相同的縮排
  14. docstring ,開頭一行寫上傳回值,接下來一行寫函數功能描述,後可按照格式>>>func(arg1, arg2, arg3) /r 傳回值。以便於測試
  15. 另外,若要使用subversion,cvs等原始程式碼控制工具。可以在函數的docstring 之後,code之前 寫上
    1.  __version__ = "$Revision:16dd63848921$"
 命名規則:
  1. 盡量少用 'l' (lowercase letter el), 'O' (uppercase letter oh), or 'I' (uppercase letter eye) 單字母作為變數的命名.-------no l,I,O
  2. 包和模組應該用短且全小寫字母(Modules should have short, all-lowercase names.):thismoduleisnew
  3. class name 則建議用CapWords(首字母大寫)的形式命名:NewClassName
  4. Exception類則用以Error結尾的字串命名為宜: NewError
  5. 全域變數盡量只是設計用於模組內使用,並且可以用import *時,包內的__all__機制來除去全域變數
  6. 函數名(function name) 盡量都用小寫且單詞間以_(底線)串連,另外,大小混合的mixedCase植被允許用於傳統類中。function_name(arg1...)
  7. 函數和方法參數(function and method arguments),self作為執行個體方法的第一個參數,cls作為類方法的第一個參數,倘若參數名與關鍵字相同,為了避諱,則應該加個底線
  8. 方法名&類執行個體的屬性(method name & instance variable)方法名規則與函數名相同,類執行個體私人屬性 和 類執行個體的私人方法以單個底線開頭_private_fucntion_name(self)
  9. 常量;全大寫,單詞間以_下弧線間隔:THIS_IS_CONSTANT_VAR
  10. 物件導向設計建議:
    1. 若對類執行個體中的屬性是設定成public的好還是private好,可以考慮先設定成private,其修改成本更低。
    2. private不能被第三方使用,因為隨時有可能被刪除、廢棄
    3. public屬性不能用底線開頭
    4. 避免屬性使用大運算量操作
    5. 倘若不想被子類繼承的屬性,應該用雙底線開頭,且最後沒有底線。這樣會啟動python的命名識別矯正處理演算法,保證不被繼承
  
  1. joined_lower 可以是函數名 方法名 屬性名稱
  2. ALL_CAPS 是常量
  3. StudlyCaps是類名
  4. camelCase 只有在預先訂製好的命名規範中使用
  5. 屬性 interface,_internal, __private
  6. 盡量避免__private形式,下面兩個串連解釋了為什麼python中沒有private聲明
  最後沒時間翻譯了,有時間再來。 Reference: http://www.python.org/dev/peps/pep-0008/#naming-conventions   Programming Recommendations
  • Code should be written in a way that does not disadvantage other implementations of Python (PyPy, Jython, IronPython, Cython, Psyco, and such).

    For example, do not rely on CPython's efficient implementation of in-place string concatenation for statements in the form a += b or a = a + b. Those statements run more slowly in Jython. In performance sensitive parts of the library, the ''.join() form should be used instead. This will ensure that concatenation occurs in linear time across various implementations.

  • Comparisons to singletons like None should always be done with is or is not, never the equality operators.

    Also, beware of writing if x when you really mean if x is not None -- e.g. when testing whether a variable or argument that defaults to None was set to some other value. The other value might have a type (such as a container) that could be false in a boolean context!

  • When implementing ordering operations with rich comparisons, it is best to implement all six operations (__eq__, __ne__, __lt__, __le__, __gt__, __ge__) rather than relying on other code to only exercise a particular comparison.

    To minimize the effort involved, the functools.total_ordering() decorator provides a tool to generate missing comparison methods.

    PEP 207 indicates that reflexivity rules are assumed by Python. Thus, the interpreter may swap y > x with x < y, y >= x with x <= y, and may swap the arguments of x == y and x != y. The sort() and min() operations are guaranteed to use the < operator and the max() function uses the > operator. However, it is best to implement all six operations so that confusion doesn't arise in other contexts.

  • Use class-based exceptions.

    String exceptions in new code are forbidden, because this language feature is being removed in Python 2.6.

    Modules or packages should define their own domain-specific base exception class, which should be subclassed from the built-in Exception class. Always include a class docstring. E.g.:

    class MessageError(Exception):    """Base class for errors in the email package."""

    Class naming conventions apply here, although you should add the suffix "Error" to your exception classes, if the exception is an error. Non-error exceptions need no special suffix.

  • When raising an exception, use raise ValueError('message') instead of the older form raise ValueError, 'message'.

    The paren-using form is preferred because when the exception arguments are long or include string formatting, you don't need to use line continuation characters thanks to the containing parentheses. The older form will be removed in Python 3.

  • When catching exceptions, mention specific exceptions whenever possible instead of using a bare except: clause.

    For example, use:

    try:    import platform_specific_moduleexcept ImportError:    platform_specific_module = None

    A bare except: clause will catch SystemExit and KeyboardInterrupt exceptions, making it harder to interrupt a program with Control-C, and can disguise other problems. If you want to catch all exceptions that signal program errors, use except Exception: (bare except is equivalent to except BaseException:).

    A good rule of thumb is to limit use of bare 'except' clauses to two cases:

    1. If the exception handler will be printing out or logging the traceback; at least the user will be aware that an error has occurred.
    2. If the code needs to do some cleanup work, but then lets the exception propagate upwards with raise. try...finally can be a better way to handle this case.
  • Additionally, for all try/except clauses, limit the try clause to the absolute minimum amount of code necessary. Again, this avoids masking bugs.

    Yes:

    try:    value = collection[key]except KeyError:    return key_not_found(key)else:    return handle_value(value)

    No:

    try:    # Too broad!    return handle_value(collection[key])except KeyError:    # Will also catch KeyError raised by handle_value()    return key_not_found(key)
  • Context managers should be invoked through separate functions or methods whenever they do something other than acquire and release resources. For example:

    Yes:

    with conn.begin_transaction():    do_stuff_in_transaction(conn)

    No:

    with conn:    do_stuff_in_transaction(conn)

    The latter example doesn't provide any information to indicate that the __enter__ and __exit__ methods are doing something other than closing the connection after a transaction. Being explicit is important in this case.

  • Use string methods instead of the string module.

    String methods are always much faster and share the same API with unicode strings. Override this rule if backward compatibility with Pythons older than 2.0 is required.

  • Use ''.startswith() and ''.endswith() instead of string slicing to check for prefixes or suffixes.

    startswith() and endswith() are cleaner and less error prone. For example:

    Yes: if foo.startswith('bar'):No:  if foo[:3] == 'bar':

    The exception is if your code must work with Python 1.5.2 (but let's hope not!).

  • Object type comparisons should always use isinstance() instead of comparing types directly.

    Yes: if isinstance(obj, int):No:  if type(obj) is type(1):

    When checking if an object is a string, keep in mind that it might be a unicode string too! In Python 2.3, str and unicode have a common base class, basestring, so you can do:

    if isinstance(obj, basestring):
  • For sequences, (strings, lists, tuples), use the fact that empty sequences are false.

    Yes: if not seq:     if seq:No: if len(seq)    if not len(seq)
  • Don't write string literals that rely on significant trailing whitespace. Such trailing whitespace is visually indistinguishable and some editors (or more recently, reindent.py) will trim them.

  • Don't compare boolean values to True or False using ==.

    Yes:   if greeting:No:    if greeting == True:Worse: if greeting is True:
  • The Python standard library will not use function annotations as that would result in a premature commitment to a particular annotation style. Instead, the annotations are left for users to discover and experiment with useful annotation styles.

    Early core developer attempts to use function annotations revealed inconsistent, ad-hoc annotation styles. For example:

    • [str] was ambiguous as to whether it represented a list of strings or a value that could be either str or None.
    • The notation open(file:(str,bytes)) was used for a value that could be either bytes or str rather than a 2-tuple containing a str value followed by abytes value.
    • The annotation seek(whence:int) exhibited an mix of over-specification and under-specification: int is too restrictive (anything with __index__ would be allowed) and it is not restrictive enough (only the values 0, 1, and 2 are allowed). Likewise, the annotation write(b: bytes) was also too restrictive (anything supporting the buffer protocol would be allowed).
    • Annotations such as read1(n: int=None) were self-contradictory since None is not an int. Annotations such as source_path(self, fullname:str) -> objectwere confusing about what the return type should be.
    • In addition to the above, annotations were inconsistent in the use of concrete types versus abstract types: int versus Integral and set/frozenset versus MutableSet/Set.
    • Some annotations in the abstract base classes were incorrect specifications. For example, set-to-set operations require other to be another instance of Set rather than just an Iterable.
    • A further issue was that annotations become part of the specification but weren't being tested.
    • In most cases, the docstrings already included the type specifications and did so with greater clarity than the function annotations. In the remaining cases, the docstrings were improved once the annotations were removed.
    • The observed function annotations were too ad-hoc and inconsistent to work with a coherent system of automatic type checking or argument validation. Leaving these annotations in the code would have made it more difficult to make changes later so that automated utilities could be supported.
  
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.