---
# System prepended metadata

title: pep8 Style Guide for python code
tags: [python]

---

pep8 Style Guide for python code
===

Date: 2017-06-21 17:04:24
###### tags: `python`

# pep8 Style Guide for Python Code
之前開發都沒在遵守coding style的(XD)，不過當程式碼越寫越長時，有些coding style還是遵守好。

* Use 4-space indentation, and no tabs.
    * 用4個space取代tab

> 4 spaces are a good compromise between small indentation (allows greater nesting depth) and large indentation (easier to read). Tabs introduce confusion, and are best left out.

* Wrap lines so that they don’t exceed 79 characters.
    * 一行不要超過79characters
    * 可以用\接起來
    
> This helps users with small displays and makes it possible to have several code files side-by-side on larger displays.

* Use blank lines to separate functions and classes, and larger blocks of code inside functions.
    用空白號區隔function 和class
> When possible, put comments on a line of their own.

* Use docstrings.
    * 超方便的，一定要會
* Use spaces around operators and after commas, but not directly inside bracketing constructs: a = f(1, 2) + g(3, 4).

* Name your classes and functions consistently; the convention is to use `CamelCase` for classes and `lower_case_with_underscores` for functions and methods. Always use self as the name for the first method argument (see A First Look at Classes for more on classes and methods).
    CamelCase for class,底限for function和class methods
* Don’t use fancy encodings if your code is meant to be used in international environments. Python’s default, UTF-8, or even plain ASCII work best in any case.
    請用utf-8和ASCII
* Likewise, don’t use non-ASCII characters in identifiers if there is only the slightest chance people speaking a different language will read or maintain the code.
    不要使用non-ASCII字串別人的電腦可能會無法顯示
> 當然故意要讓別人看不懂當然可以用(誤

## imports
* Imports should usually be on separate lines
```python
import os,sys
```
not good,do this instead
```python
import os
import sys
```
* Imports should be grouped in the following order:

    1. standard library imports
    2. related third party imports
    3. local application/library specific imports
   
* Absolute imports are recommended, as they are usually more readable and tend to be better behaved (or at least give better error messages) if the import system is incorrectly configured (such as when a directory inside a package ends up on sys.path ):
```python
import mypkg.sibling
from mypkg import sibling
from mypkg.sibling import example
```

    However, explicit relative imports are an acceptable alternative to absolute imports, especially when dealing with complex package layouts where using absolute imports would be unnecessarily verbose:
```python
from . import sibling
from .sibling import example
```
<div class="alert alert-lock alert-warning">
Standard library code should avoid complex package layouts and always use absolute imports.
</div>
<div class="alert alert-block alert-danger">
Implicit relative imports should never be used and have been removed in Python 3.
</div>
* avoid Wildcard imports(from module import \*)

## Module level dunder names
Module level "dunders" (i.e. names with two leading and two trailing underscores) such as __all__ , __author__ , __version__ , etc. should be placed after the module docstring but before any import statements except from __future__ imports. Python mandates that future-imports must appear in the module before any other code except docstrings.

For example:

"""This is the example module.

This module does stuff.
"""

from __future__ import barry_as_FLUFL

__all__ = ['a', 'b', 'c']
__version__ = '0.1'
__author__ = 'Cardinal Biggles'

import os
import sys

## trailing commas
```python
# yes
file=('vim.txt',)
# ok but confusing
file='vim.txt',
```

```python

# Yes:

FILES = [
    'setup.cfg',
    'tox.ini',
    ]
initialize(FILES,
           error=True,
           )
# No:

FILES = ['setup.cfg', 'tox.ini',]
initialize(FILES, error=True,)
```
> list不分段感覺沒有比較糟，不過當contents多時第一種明顯比較好

## Programming Recommendations
* for all try/except clauses, limit the try clause to the absolute minimum amount of code necessary. Again, this avoids masking bugs.

```python
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)
```

* Be consistent in return statements. Either

```python
Yes:

def foo(x):
    if x >= 0:
        return math.sqrt(x)
    else:
        return None

def bar(x):
    if x < 0:
        return None
    return math.sqrt(x)
No:

def foo(x):
    if x >= 0:
        return math.sqrt(x)

def bar(x):
    if x < 0:
        return
    return math.sqrt(x)
```

* For sequences, (strings, lists, tuples), use the fact that empty sequences are false.

```python
Yes: if not seq:
     if seq:

No: if len(seq):
    if not len(seq):
```

# Ref 
[pep8](https://www.python.org/dev/peps/pep-0008/#id9)
