Coding Standards
This section defines conventions and best practices for writing clean, maintainable, and consistent Python and Django code. Adhering to these standards ensures readability, reduces bugs, and improves collaboration across teams.
Naming Conventions
Variables
Use descriptive, lowercase names with underscores for variables. Avoid single-letter or ambiguous names.
# Good
user_name = 'John Doe'
invoice_total = 1500
# Bad
u = 'John Doe'
x = 1500
Methods
Method names should be in snake_case and clearly describe their purpose. Use verbs for actions.
# Good
def get_user_name(self):
return 'John Doe'
def calculate_invoice_total(self, items):
# ...
# Bad
def getuser(self):
return 'John Doe'
def calc(self):
# ...
Classes
Class names should use PascalCase and be singular, representing a single entity or concept.
# Good
class UserManager:
pass
class Invoice:
pass
# Bad
class user_manager:
pass
class invoices:
pass
Constants
Constants should be in UPPER_CASE with underscores. Use them for values that do not change.
# Good
MAX_USER_COUNT = 100
DEFAULT_TIMEOUT = 30
# Bad
maxUserCount = 100
defaultTimeout = 30
Formatting
Indentation
Use 4 spaces per indentation level. Do not use tabs.
# Good
if condition:
print('true')
# Bad
if condition: print('true')
Line Length
Keep lines under 80 characters. Break long statements into multiple lines.
# Good
long_string = (
'This is a long string that is split across multiple lines to keep each line under 80 characters.'
)
Blank Lines
Use blank lines to separate logical sections of code, such as between methods or class definitions.
# Good
def first_function():
pass
def second_function():
pass
# Bad
def first_function():
pass
def second_function():
pass
Comments
Use comments to explain non-obvious code. Write comments above the code they describe, not inline. Avoid redundant comments.
# Good
# This method returns the user's name
def get_user_name(self):
return 'John Doe'
# Explain complex logic
# Calculate the total invoice amount including tax
def calculate_invoice_total(self, items):
# ...
# Bad
def get_user_name(self):
return 'John Doe' # returns name
Additional Best Practices
- Use type hints for function arguments and return types where possible.
- Group related methods and classes together in files and folders.
- Avoid magic numbers and strings; use named constants instead.
- Follow PEP 8 as a baseline for formatting and structure.
- Refactor duplicated code into reusable methods or classes.
- Write self-documenting code: code should be clear enough that comments are only needed for complex logic.
Example: Comprehensive Class
class UserManager:
"""
Manages user operations such as registration and authentication.
"""
def register(self, data: dict) -> 'User':
# ... registration logic ...
pass
def authenticate(self, email: str, password: str) -> bool:
# ... authentication logic ...
pass