🐍 Python - Naming
Be consistent with your naming. Always consider following naming guidelines of libraries and frameworks you use. Here is naming rules I use in my own projects.
variables_are_in_snake_case
functions_are_in_snake_case()
my_class.public_instance_variables_are_in_snake_case
my_class.public_methods_are_in_snake_case()
_underscore_communicates_that_it_should_not_be_used_outside_of_the_module_py
ClassesAreInPascalCase
TypesAreInPascalCase
AcronymsAreInAllCapsLOL
HTTPServerError # (not HttpServerError)
CONSTANTS_ARE_IN_UPPER_SNAKE_CASE
"Dunder" means "double-underscore" when talking or reading about Python. This refers to Python methods with special meaning that start and end with __
.
class A:
def __init__(self) -> None:
# "dunder init"
pass
Avoid trailing underscores. Some people use trailing underscore to avoid conflicts with Python keywords. Avoid using those, find a synonym to replace the word.
# bad
my_object.add_style(master, class_='ClassName')
# good
my_object.add_style(master, name='ClassName')
my_object.add_style(master, genre='ClassName')
my_object.add_style(master, style='ClassName')
my_object.add_style(master, styleClass='ClassName')
my_object.add_style(master, className='ClassName')
Use a single underscore _
for unused values.
for _ in range(5):
print('Hello, World.')
_, age = get_name_and_age()
Never introduce new symbols with double leading and trailing underscores. Double leading and trailing underscores mean "magic".
__init__
__import__
All file and directory names are in snake_case. Even files containing just a single class named in PascalCase.
models.py
urls.py
class SendUpdateView: => send_update_view.py
class HTTPResponse: => http_response.py
Thus modules names are in snake_case. Module name may be for the collection of loose functionality or a single class. Module name is the same as the file name.
module_name.py
Thus packages names are in snake_case. Underscores are to be avoided, but they are grudgingly allowed.
# good
superpackage/
# if you must...
super_package/
Sources
- PEP 8
- Style Guide For Python Code
- Django Coding Style
- Google Python Guide
- Python Newbie Mistakes
- Learn Python in Y minutes
- Python’s null equivalent: None
- Python Idioms
- Python Best Practice Patterns
- Become More Advanced: Master the 10 Most Common Python Programming Problems
- Python Tricks The Book, Dan Bader
- Fluent Python, Luciano Ramalho