01. Coding Conventions¶
Overview¶
This guide defines the coding conventions can be used in Python project to ensure readability, consistency, and maintainability. All conventions are aligned with Python community standards, internal best practices, and tooling support (e.g. linters, formatters).
Naming convetion is a convention for naming things. Conventions differ in their intents and it's support multiple use cases, especially in computer programing.
The potential benefits for development teams:
-
To provide additional information
-
To help formalize expectations and promote consistency within team
-
To enhance the aesthetic and professional appearance of work product
Use Cases:
There are several use cases:
-
Folder and file naming conventions
-
Naming conventions for projects, repositories, and packages
-
Tagging versions of targeted models
How to start:
For Python, the PEP-008 is the headstart is very important
A Foolish Consistency is the Hobgoblin of Little Minds
One of Guido"s key insights is that code is read much more often than it is written. The guidelines provided here are intended to improve the readability of code and make it consistent across the wide spectrum of Python code. As PEP 20 says, "Readability counts".
A style guide is about consistency. Consistency with this style guide is important. Consistency within a project is more important. Consistency within one module or function is the most important.
However, know when to be inconsistent – sometimes style guide recommendations just aren"t applicable. When in doubt, use your best judgment. Look at other examples and decide what looks best. And don"t hesitate to ask!
In particular: do not break backwards compatibility just to comply with this PEP!
Some other good reasons to ignore a particular guideline:
When applying the guideline would make the code less readable, even for someone who is used to reading code that follows this PEP. To be consistent with surrounding code that also breaks it (maybe for historic reasons) – although this is also an opportunity to clean up someone else"s mess (in true XP style). Because the code in question predates the introduction of the guideline and there is no other reason to be modifying that code. When the code needs to remain compatible with older versions of Python that don"t support the feature recommended by the style guide.
So much learn from the previous. I captured it's when
I learned alot from PEP008 - which surraound me the pros/cons of each style. When and how to apply to the team
Guidelines¶
Naming Conventions¶
Consistent naming makes code easier to read, review, and maintain. Follow these rules when defining objects, classes, functions, and modules.
| Element | Convention | Example |
|---|---|---|
| Constants | UPPER_SNAKE_CASE | REQUIRED_COLUMNS |
| Classes | CamelCase | ResponseAdjustment |
| Functions | snake_case | get_element() |
| Variables | snake_case | total_count |
| Modules | snake_case | data_loader.py |
The project namespace should be following:
-
Short and easy to remember
-
Avoid too much using
w,i,l,r -
From a space that contain a relative characteristics.
-
Using
-as much as possible, without using_
Dependency Management (requirements.txt)¶
All external packages required to run or test the project must be declared explicitly.
| Rule | Description |
|---|---|
| Declare dependencies | Add all required packages to requirements.txt |
| Avoid implicit installs | Do not rely on global or system-installed packages |
| Version pinning | Pin versions where stability is important |
Example:
Import Style¶
Choose the import style based on clarity, namespace safety, and readability. Python caches imported modules, so repeated imports do not reload the module.
| Import Style | When to Use | Example |
|---|---|---|
import module | Preferred for large or shared modules | import numpy as np |
from module import x | When importing a small, clear API | from pathlib import Path |
| Avoid wildcard imports | Reduces clarity and tooling support | Don't use from module import * |
Recommended:
-
Prefer explicit imports for readability
-
Avoid name collisions
-
Keep imports consistent across the codebase
-
Group imports: standard → third-party → local
Performance & Initialization Considerations¶
Imports can affect application startup time, especially in large projects.
| Practice | Recommendation |
|---|---|
| Heavy imports | Move inside functions if rarely used |
| Top-level imports | Use for core dependencies |
| Circular imports | Refactor modules to avoid them |
Example:
Tooling Support¶
These conventions are enforced and supported by automated tools:
| Tool | Purpose |
|---|---|
ruff | Linting and style enforcement |
pre-commit | Automatic checks before commits |
| IDEs | Autocomplete, refactoring, static analysis |
Error Handling & Exceptions¶
Handle errors explicitly to improve reliability and debuggability.
| Rule | Recommendation | Example |
|---|---|---|
| Catch specific exceptions | Avoid bare except: | except ValueError: |
| Preserve context | Re-raise or chain exceptions | raise CustomError() from exc |
| Avoid silent failures | Always log or surface errors | Don't use pass |
Logging Conventions¶
Use structured, consistent logging instead of print.
| Level | When to Use |
|---|---|
DEBUG | Development diagnostics |
INFO | Normal application flow |
WARNING | Recoverable issues |
ERROR | Failed operations |
import logging
logger = logging.getLogger(__name__)
logger.info("Job started", extra={"job_id": job_id})
Function & Method Design¶
Functions should be small, predictable, and easy to test.
| Guideline | Description |
|---|---|
| Single responsibility | One function = one purpose |
| Explicit returns | Avoid implicit None |
| Limit parameters | Prefer ≤ 5 parameters |
Type Hints & Static Typing¶
Type hints improve readability and enable static analysis.
| Rule | Recommendation |
|---|---|
| Public APIs | Always type-hinted |
| Complex structures | Use TypedDict, dataclass |
| Optional values | Use Optional[T] |
Documentation & Docstrings¶
Document why something exists, not just what it does.
| Element | Convention |
|---|---|
| Public functions | Google-style docstrings |
| Modules | Describe purpose & usage |
| TODOs | Include owner or ticket |
def load_config(path: str) -> dict:
"""Load application configuration from file.
Args:
path: Path to the config file.
Returns:
Parsed configuration dictionary.
"""
Immutability & Side Effects¶
Reduce hidden side effects to make behavior predictable.
| Practice | Recommendation |
|---|---|
| Avoid mutating inputs | Return new objects |
| Global state | Minimize usage |
| Defaults | Never use mutable defaults |
Configuration & Secrets Management¶
Configuration and secrets must be handled securely and consistently to avoid leaks and environment-specific bugs.
| Rule | Guideline | Example |
|---|---|---|
| Separate config from code | Never hard-code config values | Don't use API_KEY = "abc123" |
| Use environment variables | Load secrets at runtime | os.getenv("API_KEY") |
| Provide templates | Commit example.env only | example.env |
| Validate config | Fail fast on missing values | Raise error on startup |
Recommended:
-
Secrets must never be committed to version control
-
Use
.envfiles for local development only -
Production secrets should come from a secure store
Futher reading¶
[4] Naming guidance is inspired by established conventions such as the .NET Framework naming guidances
[5] PEP 8 - Style Guide for Python Code
Takeaway¶
-
Use PEP8
-
Always use compiance tools in the headstart
-
Try to consitent, even when you write the violated-PEP008.
-
Focus on the output itself.
-
For Python project, heading with
rufforflake8.ruffhas a performance boot but theflake8is more concreate.
Tools supporting¶
For case you want to have the suggestion tools for the name, can use:
I based on the targeted with AI generator of https://namelix.com/
- [1] Using Pokemon Database > Pokedex > National for the namespace. Shoud be choose from Gen 6 to Gen 9
Reference¶
[1] Wikipedia - Naming convention
[2] Wikipedia - Naming convention for programming
