-
Notifications
You must be signed in to change notification settings - Fork 1
Python Code Style Guide
Roberto Preste edited this page Dec 20, 2019
·
2 revisions
Type | Convention | Example |
---|---|---|
Function | lowercase words separated by underscores | my_function |
Variable | lowercase words separated by underscores | my_variable |
Class | CamelCase words (no underscores) | MyClass |
Method | lowercase words separated by underscores | my_method |
Constant | UPPERCASE words separated by underscores | MY_CONSTANT |
Module | lowercase words separated by underscores | my_module.py |
Package | lowercase words with no underscores | mypackage |
With assignment operators, comparisons and booleans use whitespace on either side:
my_variable = 5
if my_variable > 10 and my_variable < 20:
pass
Do not use whitespace when assigning a default value in a function signature or when calling a function with keyword arguments:
def my_function(my_var=10):
pass
my_function(my_var=20)
Do not use whitespace on the internal side of brackets, parentheses, etc.
Do not use whitespace before commas, colons and semicolons; but use whitespaces after commas, colons and semicolons.
4 spaces, avoid <tab> characters.
Python3 programs won't run if tabs and spaces are mixed together. Tabs can lead to issues,
so please avoid them.
- Surround top-level functions and classes with two blank lines
class MyFirstClass: pass class MySecondClass: pass def top_level_function(): pass
- Surround methods inside classes with a single blank line
class MyClass: def first_method(self): pass def second_method(self): pass
The most commonly suggested maximum line length is 79 characters.
If not possible to comply with this rule, please use line breaks responsibly:
- strings can use parentheses:
my_long_string = ("string string string string " "string string string string " "string string string string ")
- imports can use parentheses:
from module import ( function1, function2, function3 )
- math operations on multiple lines want the operator on the next line:
total = (first + second * third)