└── README.rst /README.rst: -------------------------------------------------------------------------------- 1 | Python Style Guide 2 | ================== 3 | 4 | One memo for Python coding style. 5 | 6 | 7 | Why 8 | --- 9 | 10 | **Coding Style Matters.** 11 | 12 | If you still do not take this seriously, google `why coding style matters 13 | `_ or 14 | ask anyone who is professional. 15 | 16 | 17 | Code Layout 18 | ----------- 19 | 20 | Use 4 spaces per indentation level, no tab. 21 | 22 | Limit all lines to a maximum of 79 characters. 23 | 24 | Seperate top-level definitions with two blank lines, definitions inside should 25 | be separated by a single blank line. Extra blank lines may be used if needed. 26 | 27 | Source file should always use UTF-8 for encoding. 28 | 29 | Imports should be grouped in the following order: 30 | 31 | 1. standard library imports 32 | 2. related third party imports 33 | 3. local application/library specific imports 34 | 35 | Write docstrings for all modules, functions, classes, and methods. All 36 | docstrings should be formatted in reStructuredText as understood by Sphinx. 37 | 38 | .. code:: python 39 | 40 | # -*- coding: utf-8 -*- 41 | """ 42 | Code Layout 43 | ~~~~~~~~~~~ 44 | """ 45 | import os 46 | import sys 47 | from subprocess import Popen, PIPE 48 | 49 | import requests 50 | 51 | from app import something 52 | 53 | 54 | # Surround binary operators with a single space on either side 55 | g = "global" 56 | 57 | 58 | def long_function_name(param_one, param_two, 59 | param_three, param_four): 60 | """One demo for continuation lines. 61 | 62 | Continuation lines should align wrapped elements either vertically 63 | using Python's implicit line joining inside parentheses, brackets 64 | and braces or use backslashes, in which case you should align the 65 | next line with the last dot or equal sign or indent four spaces. 66 | """ 67 | print(param_one) 68 | print(param_two) 69 | 70 | print(param_three) 71 | print(param_four) 72 | 73 | this_is_a_very_long(function_call, 'with many parameters') \ 74 | .that_returns_an_object_with_an_attribute 75 | 76 | MyModel.query.filter(MyModel.scalar > 120) \ 77 | .order_by(MyModel.name.desc()) \ 78 | .limit(10) 79 | 80 | 81 | foo = long_function_name(var_one, var_two, 82 | var_three, var_four) 83 | 84 | 85 | my_dict = { 86 | "key": "value", 87 | "key2": "value2" 88 | } 89 | 90 | 91 | Naming Conventions 92 | ------------------ 93 | 94 | Modules and packages should have short, all-lowercase names, underscores can 95 | be used if it improves readability. 96 | 97 | Class names should use the CapWords convention. 98 | 99 | Function names should be lowercase, with words separated by underscores as 100 | necessary to improve readability. 101 | 102 | Always use ``self`` for the first argument to instance methods. 103 | 104 | Always use ``cls`` for the first argument to class methods. 105 | 106 | Use one leading underscore only for non-public methods and instance variables. 107 | 108 | Constants are usually defined on a module level and written in all capital 109 | letters with underscores separating words. 110 | 111 | .. code:: python 112 | 113 | # -*- coding: utf-8 -*- 114 | """ 115 | Naming 116 | ~~~~~~ 117 | """ 118 | 119 | TOTAL_NUMBER = 100 120 | 121 | 122 | class FooDemo(object): 123 | """FooDemo. 124 | 125 | Used for class name convention demo. 126 | """ 127 | 128 | def __init__(self, foo): 129 | self.foo = foo 130 | self._number = TOTAL_NUMBER 131 | 132 | @classmethod 133 | def name(cls): 134 | print(cls.__name__) 135 | 136 | def _double(self): 137 | return self._number * 2 138 | 139 | def get_number(self): 140 | return self._double() 141 | 142 | 143 | Recommendations 144 | --------------- 145 | 146 | Comparisons to singletons like ``None`` should always be done with ``is`` or 147 | ``is not``, never the equality operators. 148 | 149 | Always use a ``def`` statement instead of an assignment statement that binds a 150 | lambda expression directly to a name. 151 | 152 | Derive exceptions from ``Exception`` rather than ``BaseException``. 153 | 154 | When raising an exception, use ``raise ValueError('message')``. 155 | 156 | When catching exceptions, mention specific exceptions whenever possible 157 | instead of using a bare ``except:`` clause. 158 | 159 | When a resource is local to a particular section of code, use a ``with`` 160 | statement to ensure it is cleaned up promptly and reliably after use. 161 | 162 | Object type comparisons should always use ``isinstance()`` instead of comparing 163 | types directly. 164 | 165 | .. code:: python 166 | 167 | if foo is not None: 168 | pass 169 | 170 | # Do not use f = lambda x: 2 * x 171 | def f(x): return 2 * x 172 | 173 | class MyError(Exception): 174 | """My Error.""" 175 | pass 176 | 177 | try: 178 | import platform_specific_module 179 | except ImportError: 180 | platform_specific_module = None 181 | 182 | 183 | Source 184 | ------ 185 | 186 | Read the excellent code to learn more in the real world. 187 | 188 | - `Flask `_ 189 | - `Werkzeug `_ 190 | 191 | 192 | Links 193 | ----- 194 | 195 | - `PEP 8 `_ 196 | - `Pocoo Style Guide `_ 197 | 198 | 199 | Better 200 | ------ 201 | 202 | If you feel anything wrong, feedbacks or pull requests are welcome. 203 | --------------------------------------------------------------------------------