or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

async-processing.mdconfiguration.mderror-processing.mdindex.mdmain-interface.mdplugin-development.mdpytest-integration.mdvcs-hooks.md
tile.json

tessl/pypi-pylama

Code audit tool for python

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/pylama@8.4.x

To install, run

npx @tessl/cli install tessl/pypi-pylama@8.4.0

index.mddocs/

Pylama

Pylama is a comprehensive Python code audit and quality assurance tool that aggregates multiple popular linters and checkers into a single unified interface. It provides extensive configuration options, multiple output formats, and seamless integration into development workflows including CI/CD pipelines, pytest testing, and version control hooks.

Package Information

  • Package Name: pylama
  • Language: Python
  • Installation: pip install pylama

Core Imports

import pylama

For programmatic usage:

from pylama.main import check_paths, shell
from pylama.core import run
from pylama.config import parse_options
from pylama.errors import Error

For plugin development:

from pylama.lint import LinterV2
from pylama.context import RunContext

Basic Usage

Command Line Usage

# Check current directory
import subprocess
subprocess.run(['pylama', '.'])

# Check specific files with custom options
subprocess.run(['pylama', '--linters=pycodestyle,pyflakes', 'myfile.py'])

# Generate JSON output
subprocess.run(['pylama', '--format=json', '.'])

Programmatic Usage

from pylama.main import check_paths
from pylama.config import parse_options

# Parse options and check files
options = parse_options(['--linters=pycodestyle,pyflakes', 'myfile.py'])
errors = check_paths(['myfile.py'], options)

# Process errors
for error in errors:
    print(f"{error.filename}:{error.lnum} - {error.message}")

Pytest Integration

# pytest automatically discovers the pylama plugin
# Run tests with pylama checking
import subprocess
subprocess.run(['pytest', '--pylama'])

Architecture

Pylama follows a plugin-based architecture that enables extensibility and modularity:

  • Core Engine: Manages file processing, error collection, and result formatting
  • Configuration System: Handles multiple config file formats and command-line options
  • Plugin Framework: Standardized interface for integrating diverse linters and checkers
  • Context Management: Provides execution context with resource management and error tracking
  • Error Processing: Deduplicates errors across linters and provides flexible output formatting

This design allows pylama to serve as a unified front-end for the Python quality assurance ecosystem, supporting both built-in linters (pycodestyle, pyflakes, mccabe, pydocstyle, pylint, mypy, radon, eradicate, vulture) and custom plugin development.

Capabilities

Main Interface Functions

Core functions for running code analysis programmatically and via command line interface.

def shell(args: List[str] = None, error: bool = True):
    """Main console entry point for pylama command."""

def check_paths(
    paths: Optional[List[str]],
    options: Namespace,
    code: str = None,
    rootdir: Path = None,
) -> List[Error]:
    """Check multiple file paths for code quality issues."""

def run(
    path: str,
    code: str = None,
    rootdir: Path = CURDIR,
    options: Namespace = None
) -> List[Error]:
    """Run code checkers on a single file."""

Main Interface

Configuration Management

Comprehensive configuration system supporting multiple file formats and extensive customization options.

def parse_options(
    args: List[str] = None,
    config: bool = True,
    rootdir: Path = CURDIR,
    **overrides
) -> Namespace:
    """Parse command line arguments and configuration files."""

def get_config(user_path: str = None, rootdir: Path = None) -> inirama.Namespace:
    """Load configuration from available config files."""

def setup_parser() -> ArgumentParser:
    """Create argument parser with all command line options."""

def setup_logger(options: Namespace):
    """Setup logging based on options."""

Configuration

Error Handling and Processing

Error representation, deduplication, and formatting capabilities.

class Error:
    """Represents a single linting error."""
    def __init__(
        self,
        source: str = "pylama",
        col: int = 1,
        lnum: int = 1,
        type: str = None,
        text: str = "unknown error",
        filename: str = "",
        number: str = ""
    ): ...

def remove_duplicates(errors: List[Error]) -> Generator[Error, None, None]:
    """Remove duplicate errors from different linters."""

def display_errors(errors: List[Error], options: Namespace):
    """Format and display errors using specified format."""

Error Processing

Plugin Development Framework

Framework for creating custom linters and extending pylama functionality.

class LinterV2(Linter):
    """Base class for modern linter plugins."""
    name: Optional[str] = None
    
    def run_check(self, ctx: RunContext):
        """Check code using RunContext."""

class RunContext:
    """Execution context for linter operations."""
    def __init__(self, filename: str, source: str = None, options: Namespace = None): ...
    def get_params(self, lname: str) -> dict: ...
    def push(self, source: str, **err_info): ...

Plugin Development

Pytest Integration

Seamless integration with pytest for automated code quality checking during testing.

def pytest_addoption(parser):
    """Add --pylama option to pytest."""

def pytest_collect_file(path, parent):
    """Collect Python files for pylama checking."""

class PylamaError(Exception):
    """Exception raised when pylama checks fail."""

class PylamaItem(pytest.Item):
    """Pytest test item for pylama checks."""

Pytest Integration

Asynchronous Processing

High-performance parallel processing capabilities for large codebases.

def check_async(
    paths: List[str],
    code: str = None,
    options: Namespace = None,
    rootdir: Path = None
) -> List[Error]:
    """Check files asynchronously using process pool."""

Async Processing

Version Control Hooks

Pre-commit and post-commit hooks for Git and Mercurial integration.

def git_hook(error: bool = True):
    """Git pre-commit hook implementation."""

def hg_hook(_, repo, node=None, **kwargs):
    """Mercurial commit hook implementation."""

def install_hook(path: str):
    """Auto-detect VCS and install appropriate hook."""

VCS Hooks

Types

from argparse import Namespace
from pathlib import Path
from typing import Generator, Any, List, Optional, Dict, Set, Tuple

class Error:
    """Linting error representation."""
    filename: str
    lnum: int
    col: int
    message: str  # Error message text
    etype: str
    source: str
    number: str
    
    def to_dict(self) -> Dict[str, Any]: ...
    def format(self, template: str) -> str: ...

class RunContext:
    """Execution context for linter operations."""
    errors: List[Error]
    options: Optional[Namespace]
    skip: bool
    ignore: Set[str]
    select: Set[str]
    linters: List[str]
    filename: str
    
    def get_params(self, lname: str) -> Dict[str, Any]: ...
    def push(self, source: str, **err_info): ...

class LinterV2:
    """Modern linter base class."""
    name: Optional[str]
    
    def run_check(self, ctx: RunContext): ...

# Configuration constants
DEFAULT_LINTERS: Tuple[str, str, str]  # ("pycodestyle", "pyflakes", "mccabe")
CONFIG_FILES: List[str]  # Supported config file names
DEFAULT_FORMAT: str  # Default error message format
MESSAGE_FORMATS: Dict[str, str]  # Available message formats