Enterprise-ready Python development incorporating Kaizen (continuous improvement) and Monozukuri (meticulous craftsmanship) principles...
Build bulletproof, enterprise-ready Python applications that embody Kaizen (continuous improvement) and Monozukuri (meticulous craftsmanship) principles. This skill guides development of clean, efficient, performant Python code that is simple, elegant, and built to last.
Kaizen (改善): Continuous improvement through incremental refinement Monozukuri (ものづくり): The art of making things with meticulous attention to quality and craftsmanship
These principles translate to Python code that is:
Before writing code:
Plan the architecture:
Simplicity First
Clean Code Standards
Type Hints Best Practices
# type: ignore only when truly necessary)typing module: Optional, Union, TypeVar, GenericProtocol for structural subtypingTypedDict for dictionary shapesError Handling
except:Security Mindset
Algorithm Optimization
cProfile, line_profiler)functools.lru_cache for expensive computations__slots__ for memory-heavy classesAsync and Concurrency
asyncio for I/O-bound operationsmultiprocessing for CPU-bound operationsconcurrent.futures for simple parallelismImport Optimization
__all__ to control public APIComprehensive Testing
Logging and Observability
logging module with proper levelsDocumentation
Continuously improve:
project-name/
├── src/
│ └── project_name/
│ ├── __init__.py
│ ├── main.py # Entry point
│ ├── config.py # Configuration
│ ├── models/ # Data models
│ │ ├── __init__.py
│ │ └── user.py
│ ├── services/ # Business logic
│ │ ├── __init__.py
│ │ └── user_service.py
│ ├── repositories/ # Data access
│ │ ├── __init__.py
│ │ └── user_repo.py
│ ├── api/ # API layer
│ │ ├── __init__.py
│ │ └── routes.py
│ └── utils/ # Helpers
│ ├── __init__.py
│ └── validators.py
├── tests/
│ ├── __init__.py
│ ├── conftest.py # Pytest fixtures
│ ├── unit/
│ └── integration/
├── pyproject.toml # Project config (PEP 518)
├── README.md
└── .env.example
Modules/Packages: snake_case (user_service.py, data_processing)
Classes: PascalCase (UserService, DataProcessor, HTTPClient)
Functions/Methods: snake_case (fetch_user, calculate_total, process_data)
Constants: UPPER_SNAKE_CASE (API_URL, MAX_RETRIES, DEFAULT_TIMEOUT)
Private: Leading underscore (_internal_method, _helper_function)
Type Variables: Single uppercase or PascalCase (T, KeyType, ValueType)
# GOOD: Type hints and dataclasses
from dataclasses import dataclass
from typing import Optional
@dataclass(frozen=True, slots=True)
class User:
id: str
email: str
name: str
is_active: bool = True
# GOOD: Pydantic for validation
from pydantic import BaseModel, EmailStr, Field
class CreateUserRequest(BaseModel):
email: EmailStr
name: str = Field(min_length=1, max_length=100)
age: int = Field(ge=0, le=150)
# GOOD: Context managers for resources
from contextlib import contextmanager
from typing import Generator
@contextmanager
def database_transaction(db: Database) -> Generator[Session, None, None]:
session = db.create_session()
try:
yield session
session.commit()
except Exception:
session.rollback()
raise
finally:
session.close()
# GOOD: Async with proper error handling
async def fetch_user(user_id: str) -> User | None:
try:
async with httpx.AsyncClient() as client:
response = await client.get(f"{API_URL}/users/{user_id}")
response.raise_for_status()
return User(**response.json())
except httpx.HTTPStatusError as e:
if e.response.status_code == 404:
return None
raise UserFetchError(f"Failed to fetch user: {e}") from e
# GOOD: Dependency injection
class UserService:
def __init__(self, repo: UserRepository, cache: Cache) -> None:
self._repo = repo
self._cache = cache
async def get_user(self, user_id: str) -> User | None:
if cached := await self._cache.get(f"user:{user_id}"):
return User(**cached)
user = await self._repo.find_by_id(user_id)
if user:
await self._cache.set(f"user:{user_id}", user.model_dump())
return user
For complex scenarios, consult:
# Use built-in generics (no typing import needed)
def process_items(items: list[str]) -> dict[str, int]:
return {item: len(item) for item in items}
# Use | for unions
def fetch_data(id: str) -> User | None:
...
# Use TypedDict for structured dicts
from typing import TypedDict
class Config(TypedDict):
host: str
port: int
debug: bool
def handle_response(response: dict) -> str:
match response:
case {"status": "success", "data": data}:
return f"Success: {data}"
case {"status": "error", "message": msg}:
return f"Error: {msg}"
case {"status": status}:
return f"Unknown status: {status}"
case _:
return "Invalid response"
from pydantic_settings import BaseSettings
class Settings(BaseSettings):
database_url: str
api_key: str
debug: bool = False
max_connections: int = 10
class Config:
env_file = ".env"
settings = Settings()
Before finalizing code:
# type: ignore without justificationexcept: clausesApply this skill whenever:
This skill transforms good Python code into exceptional Python applications—fast, secure, maintainable, and delightful to work with.
