| layout | post |
|---|---|
| title | Python Coding Style Guide |
| category | AUTOSAR |
| comments | true |
This document defines the coding style for Python code in the AS project. The style is derived from analyzing existing codebase patterns and best practices for PyQt5 development and general Python programming.
- Use PascalCase (CamelCase with uppercase first letter)
- Examples:
class JsonEditor(QMainWindow): # Good class DataProcessor: # Good class UIGroup(QScrollArea): # Good class StringValidator: # Good
- Use camelCase (lowercase first letter, uppercase subsequent words)
- Private methods start with single underscore
_followed by camelCase - Examples:
def isValid(self, value): # Good def onTextChanged(self): # Good def _updateTreeIcon(self): # Good - private def _validateInput(self, data): # Good - private
- Use camelCase (lowercase first letter, uppercase subsequent words)
- Private attributes start with single underscore
_followed by camelCase - Examples:
titleText = "<b>%s</b>" % module # Good self._hasIssue = False # Good - private attribute self._fieldAnnotations = {} # Good userName = "admin" # Good
- Use ALL_UPPER_CASE with underscores for word separation
- Place at module level before classes
- Examples:
BASIC_TYPES = ["string", "integer", "bool", "number"] # Good C_CHAR_WIDTH = 14 # Good MAX_CONNECTIONS = 100 # Good THIS_IS_A_CONSTANT = 3 # Good
- Use 4 spaces for indentation
- Never use tabs
- Example:
def onTextChanged(self): text = str(self.text()) self.obj.set(self.title, text) if text != vs: self.setText(vs)
- Maximum 100 characters per line
- Break long lines with parentheses
- Examples:
# Good - line break after opening parenthesis logging.error("invalid number: %s, value=%s, text=%s" % (e, value, text)) # Good - multi-line with indentation QMessageBox( QMessageBox.Information, "Info", "invalid number: %s, value=%s, text=%s" % (e, value, text), ).exec_()
- Two blank lines between classes and functions
- One blank line between methods within a class
- No blank line after function signature before first statement
- Example:
class DataProcessor: def __init__(self, config): self.config = config ... def process(self, data): result = self._validateInput(data) ... class StringValidator: def validate(self, value): ...
- Standard library imports
- Third-party library imports (PyQt5, etc.)
- Local module imports
- Separate groups with blank lines
- Use explicit imports over wildcard imports when possible
- Example:
import logging
import re
import sys
from PyQt5 import QtCore, QtGui
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
__all__ = ["DataProcessor", "StringValidator", "logging"]- Acceptable for PyQt5 modules for brevity
- Example:
from PyQt5.QtWidgets import * # Acceptable
- Use
#for single-line comments - Comments should be in English
- Place comment above the code it describes
- Example:
# Update tree item icon based on issue severity def _updateTreeIcon(self): ...
- Use triple double quotes
""" - Provide brief description for public methods
- Include Args and Returns sections when appropriate
- Example:
def resolvePath(rootObj, path: list): """Resolve path to a tree node. Args: rootObj: Root of the tree to search path: List of path segments Returns: Tuple of (node, fieldName) where fieldName is None for tree items """ ...
- Use type hints for function parameters and return values
- Use
Optional,List,Dictfrom typing module when needed - Example:
def annotateIssue(self, issue: dict) -> None: ... def processData(data: list) -> dict: ...
- Use
assertfor debugging and type checking - Example:
assert isinstance(root, JsonModule) assert isinstance(obj, DataProcessor)
- Use try/except for expected errors
- Log errors using
logging.error() - Example:
def onTextChanged(self, text): try: value = eval(text) except Exception as e: logging.error("invalid number: %s" % e) return
- Use
pylintorflake8for static code analysis - Check for:
- Unused imports
- Undefined variables
- Code complexity
- Use
autopep8for automatic formatting - Run
python -m py_compileto check syntax errors
Version: 1.0
Date: June 2024
Based on: AS project codebase patterns