Code audit tool for python
—
Comprehensive configuration system supporting multiple file formats, command-line options, and extensive customization for all aspects of code checking. Pylama provides flexible configuration through INI files, TOML files, and command-line arguments with hierarchical precedence.
Parse and merge configuration from multiple sources with proper precedence handling.
def parse_options(
args: List[str] = None,
config: bool = True,
rootdir: Path = CURDIR,
**overrides
) -> Namespace:
"""
Parse command line arguments and configuration files.
Args:
args: Command line arguments. If None, uses sys.argv[1:]
config: Whether to load configuration files. If False, only uses command line args
rootdir: Root directory for config file search and path resolution
**overrides: Override specific configuration values
Returns:
Namespace: Parsed configuration with all options set
Configuration precedence (highest to lowest):
1. Command line arguments
2. Specified config file or auto-discovered config
3. Home directory config (~/.pylama.ini)
4. Default values
Supported config files: pylama.ini, pyproject.toml, setup.cfg, tox.ini, pytest.ini
"""Load configuration from various file formats with format-specific parsing.
def get_config(user_path: str = None, rootdir: Path = None) -> inirama.Namespace:
"""
Load configuration from available config files.
Args:
user_path: Specific config file path
rootdir: Directory to search for config files
Returns:
inirama.Namespace: Parsed configuration sections
Searches for config files in order of precedence:
- User-specified path
- pylama.ini, pyproject.toml, setup.cfg, tox.ini, pytest.ini in rootdir
- ~/.pylama.ini in home directory
"""
def get_config_ini(ini_path: str) -> inirama.Namespace:
"""
Load INI-format configuration file.
Args:
ini_path: Path to INI configuration file
Returns:
inirama.Namespace: Parsed INI configuration
"""
def get_config_toml(toml_path: str) -> inirama.Namespace:
"""
Load TOML-format configuration file.
Args:
toml_path: Path to TOML configuration file
Returns:
inirama.Namespace: Parsed TOML configuration
Requires 'toml' package for TOML parsing.
Configuration should be under [tool.pylama] section.
"""Create command-line argument parser with all available options.
def setup_parser() -> ArgumentParser:
"""
Create argument parser with all command line options.
Returns:
ArgumentParser: Configured parser with all pylama options
Includes options for:
- Linter selection and configuration
- File filtering and path handling
- Output formatting and verbosity
- Performance and concurrency settings
- Integration features (hooks, pytest)
"""Find default configuration files in standard locations.
def get_default_config_file(rootdir: Path = None) -> Optional[str]:
"""
Find default configuration file in standard locations.
Args:
rootdir: Directory to search for config files
Returns:
Optional[str]: Path to found config file or None
Search order:
1. pylama.ini
2. pyproject.toml
3. setup.cfg
4. tox.ini
5. pytest.ini
"""Helper functions for configuration processing and validation.
def parse_linters(linters: str) -> List[str]:
"""
Parse linter specification string into list.
Args:
linters: Comma-separated linter names
Returns:
List[str]: List of linter names
"""
def split_csp_str(val: Union[str, Collection[str]]) -> Set[str]:
"""
Split comma-separated string into unique values.
Args:
val: String or collection to split
Returns:
Set[str]: Set of unique values
"""
def prepare_sorter(val: Union[str, Collection[str]]) -> Optional[Dict[str, int]]:
"""
Prepare error sorting function from configuration.
Args:
val: Sort specification string or collection
Returns:
Optional[Dict[str, int]]: Sorting configuration or None for default
"""
def setup_logger(options: Namespace):
"""
Configure logging based on options.
Args:
options: Configuration options with verbosity settings
Sets up console logging with appropriate level based on:
- options.verbose: Detailed output
- options.quiet: Minimal output
"""
def fix_pathname_sep(val: str) -> str:
"""
Fix pathname separators for cross-platform compatibility.
Args:
val: Path string with potentially wrong separators
Returns:
str: Path with correct separators for current platform
"""# Linter configuration
linters: List[str] = ["pycodestyle", "pyflakes", "mccabe"] # Active linters
ignore: Set[str] = set() # Error codes to ignore
select: Set[str] = set() # Error codes to select (if specified, ignore others)
skip: List[str] = [] # File patterns to skip
# File handling
paths: List[str] = ["."] # Paths to check
format: str = "default" # Output format (default, json, pylint, pycodestyle)
sort: str = "" # Sort order for errors
# Performance
async: bool = False # Use asynchronous processing
concurrent: bool = False # Enable concurrent processing
# Line length
max_line_length: int = 79 # Maximum line length
# Output control
verbose: int = 0 # Verbosity level (0-2)
quiet: bool = False # Suppress outputEach linter can have its own configuration section:
[pylama:pycodestyle]
max_line_length = 100
ignore = E501,W503
[pylama:pylint]
ignore = R,C0111,W0613
disable = missing-docstring
[pylama:mypy]
ignore_missing_imports = Truefrom pylama.config import parse_options
# Use default configuration
options = parse_options([])
print(f"Default linters: {options.linters}")
print(f"Default format: {options.format}")from pylama.config import parse_options
# Parse specific command line options
args = [
'--linters=pycodestyle,pyflakes,mccabe',
'--ignore=E501,W503',
'--format=json',
'--max-line-length=100',
'--async',
'src/',
'tests/'
]
options = parse_options(args)
print(f"Linters: {options.linters}")
print(f"Ignore: {options.ignore}")
print(f"Paths: {options.paths}")from pylama.config import get_config
from pathlib import Path
# Load from specific config file
config = get_config("/path/to/pylama.ini")
# Load from project directory
config = get_config(rootdir=Path("./myproject"))
# Access configuration sections
pylama_config = config.get("pylama", {})
pycodestyle_config = config.get("pylama:pycodestyle", {})Example pylama.ini:
[pylama]
linters = pycodestyle,pyflakes,mccabe,pylint
ignore = D203,D213,E501
skip = migrations/*,venv/*
format = pylint
async = 1
[pylama:pycodestyle]
max_line_length = 120
[pylama:pylint]
ignore = C0111,R0903,W0613Example pyproject.toml:
[tool.pylama]
linters = ["pycodestyle", "pyflakes", "mccabe"]
ignore = ["E501", "W503"]
skip = ["migrations/*", "build/*"]
format = "json"
[tool.pylama.linter.pycodestyle]
max_line_length = 100
[tool.pylama.linter.pylint]
disable = ["missing-docstring", "too-few-public-methods"]DEFAULT_LINTERS: Tuple[str, str, str] = ("pycodestyle", "pyflakes", "mccabe")
CONFIG_FILES: List[str] = [
"pylama.ini",
"pyproject.toml",
"setup.cfg",
"tox.ini",
"pytest.ini"
]
CURDIR: Path # Current working directory
HOMECFG: Path # Home directory config file path (~/.pylama.ini)
DEFAULT_SECTION: str = "pylama" # Default configuration section nameInstall with Tessl CLI
npx tessl i tessl/pypi-pylama