API Reference
This section contains the API documentation for the pylint-sort-functions plugin.
Checker Module
Main checker class for enforcing function and method sorting.
The FunctionSortChecker is used by PyLint itself, not by end users directly. PyLint discovers this checker via the plugin entry point and manages its lifecycle.
For detailed information about the sorting rules and algorithm, see docs/sorting.rst.
- How it works:
PyLint loads the plugin and calls register() function (the plugin entry point defined in __init__.py and configured in pyproject.toml)
register() creates a FunctionSortChecker instance and gives it to PyLint
PyLint walks the AST (Abstract Syntax Tree) of user code
For each AST node, PyLint calls corresponding visit_* methods on this checker (we only implement visit_module and visit_classdef from the many available)
The checker analyzes nodes and calls self.add_message() when issues are found
- User Experience:
$ pylint –load-plugins=pylint_sort_functions mycode.py # PyLint automatically uses this checker and reports any sorting violations
The visitor pattern: PyLint calls visit_module() for modules and visit_classdef() for class definitions. Each method analyzes the code structure and reports issues.
- class pylint_sort_functions.checker.FunctionSortChecker(linter)
Bases:
BaseChecker
Checker to enforce alphabetical sorting of functions and methods.
Inherits from PyLint’s BaseChecker which provides the visitor pattern infrastructure. PyLint will automatically call our visit_* methods as it traverses the AST.
- name: str = 'function-sort'
Name of the provider.
-
msgs:
dict
[str
,Any
] = {'W9001': ('Functions are not sorted alphabetically in %s scope', 'unsorted-functions', 'Functions should be organized alphabetically within their scope (public functions first, then private functions with underscore prefix)'), 'W9002': ('Methods are not sorted alphabetically in class %s', 'unsorted-methods', 'Class methods should be organized alphabetically within their visibility scope (public methods first, then private methods with underscore prefix)'), 'W9003': ('Public and private functions are not properly separated in %s', 'mixed-function-visibility', 'Public functions (no underscore prefix) should come before private functions (underscore prefix) with clear separation'), 'W9004': ("Function '%s' should be private (prefix with underscore)", 'function-should-be-private', "Functions that are only used within their defining module should be marked as private by prefixing their name with an underscore. This rule detects functions with helper/utility naming patterns (get_, validate_, process_, helper, etc.) that are called only within the same module. Note: Cannot detect cross-module usage, so functions used by other modules won't be flagged (which reduces false positives).")}
- options: Options = (('public-api-patterns', {'default': ['main', 'run', 'execute', 'start', 'stop', 'setup', 'teardown'], 'help': 'List of function names to always treat as public API. These functions will not be flagged for privacy even if only used internally. Useful for entry points and framework callbacks.', 'metavar': '<pattern1,pattern2,...>', 'type': 'csv'}), ('enable-privacy-detection', {'default': True, 'help': 'Enable detection of functions that should be made private based on usage analysis.', 'metavar': '<y or n>', 'type': 'yn'}))
Options provided by this provider.
- visit_classdef(node)
Visit a class definition to check method sorting.
Called by PyLint for each class definition in the code.
- Parameters:
node (nodes.ClassDef) – The class definition AST node to analyze
- Return type:
None
- visit_module(node)
Visit a module node to check function sorting and privacy.
Called by PyLint once for each Python module (file) being analyzed.
- Parameters:
node (nodes.Module) – The module AST node to analyze
- Return type:
None
Messages Module
Message definitions for the pylint-sort-functions plugin.
The MESSAGES dict defines all warning/error codes that this PyLint plugin can report. Each entry creates a new PyLint message that users will see when running PyLint.
- Message Structure:
- Key: Message ID (e.g., “W9001”)
First letter: Severity (W=Warning, E=Error, C=Convention, R=Refactor)
Digits: Plugin’s unique range (9001-9999 for custom plugins)
- Value: Tuple of (template, symbol, description)
Template: Actual message shown to users (supports %s formatting)
Symbol: Human-readable name for disabling (e.g., unsorted-functions)
Description: Longer explanation for documentation/help
- Usage Examples:
In checker: self.add_message(“unsorted-functions”, node=node, args=(“module”,)) PyLint output: W9001: Functions are not sorted alphabetically in module scope (unsorted-functions) User disabling: # pylint: disable=unsorted-functions
Utilities Module
Utility functions for AST analysis and sorting logic.
This module provides the core analysis functions for the pylint-sort-functions plugin. It includes functions for:
Function/method sorting validation
Public/private function separation validation
Function privacy detection (identifying functions that should be private)
Framework-aware sorting with decorator exclusions
For detailed information about the sorting algorithm and rules, see the documentation at docs/sorting.rst which explains the complete sorting methodology, special method handling, privacy detection, and configuration options.
Function Privacy Detection: The plugin uses import analysis to identify functions that should be private by scanning actual usage patterns across the project: - Analyzes cross-module imports and function calls in all Python files - Identifies functions that are only used within their own module - Skips common public API patterns (main, run, setup, etc.) - Provides accurate detection based on real usage patterns
- pylint_sort_functions.utils.are_functions_properly_separated(functions)
Check if public and private functions are properly separated.
This function only verifies the ordering constraint: public functions must appear before private functions. It does not check for section comment headers like “# Public functions” or “# Private functions” - that would be a separate validation if implemented.
- Parameters:
functions (list[nodes.FunctionDef]) – List of function definition nodes
- Returns:
True if public functions come before private functions
- Return type:
bool
- pylint_sort_functions.utils.are_functions_sorted(functions)
Check if functions are sorted alphabetically within their visibility scope.
Functions are expected to be sorted with: - Public functions (including dunder methods like __init__) sorted first - Private functions (single underscore prefix) sorted alphabetically second
Dunder methods are treated as public and will naturally sort to the top due to the __ prefix (e.g., __init__ comes before add_item).
- Parameters:
functions (list[nodes.FunctionDef]) – List of function definition nodes
- Returns:
True if functions are properly sorted
- Return type:
bool
- pylint_sort_functions.utils.are_functions_sorted_with_exclusions(functions, ignore_decorators=None)
Check if functions are sorted alphabetically, excluding decorator-dependent ones.
This is the enhanced version of are_functions_sorted that supports framework-aware sorting by excluding functions with specific decorators that create dependencies.
- Parameters:
functions (list[nodes.FunctionDef]) – List of function definition nodes
ignore_decorators (list[str] | None) – List of decorator patterns to ignore
- Returns:
True if functions are properly sorted (excluding ignored ones)
- Return type:
bool
- pylint_sort_functions.utils.are_methods_sorted(methods)
Check if methods are sorted alphabetically within their visibility scope.
- Parameters:
methods (list[nodes.FunctionDef]) – List of method definition nodes
- Returns:
True if methods are properly sorted
- Return type:
bool
- pylint_sort_functions.utils.are_methods_sorted_with_exclusions(methods, ignore_decorators=None)
Check if methods are sorted alphabetically, excluding decorator-dependent ones.
- Parameters:
methods (list[nodes.FunctionDef]) – List of method definition nodes
ignore_decorators (list[str] | None) – List of decorator patterns to ignore
- Returns:
True if methods are properly sorted (excluding ignored ones)
- Return type:
bool
- pylint_sort_functions.utils.function_has_excluded_decorator(func, ignore_decorators)
Check if a function should be excluded from sorting due to its decorators.
Some decorators create dependencies that make alphabetical sorting inappropriate. For example, Click commands or Flask routes may need specific ordering for proper framework behavior.
- Parameters:
func (nodes.FunctionDef) – Function definition node to check
ignore_decorators (list[str] | None) – List of decorator patterns to match against
- Returns:
True if function should be excluded from sorting requirements
- Return type:
bool
- pylint_sort_functions.utils.get_functions_from_node(node)
Extract all function definitions from a module.
- Parameters:
node (nodes.Module) – Module AST node
- Returns:
List of function definition nodes
- Return type:
list[nodes.FunctionDef]
- pylint_sort_functions.utils.get_methods_from_class(node)
Extract all method definitions from a class.
- Parameters:
node (nodes.ClassDef) – Class definition node
- Returns:
List of method definition nodes
- Return type:
list[nodes.FunctionDef]
- pylint_sort_functions.utils.is_private_function(func)
Check if a function is private (starts with underscore).
Functions starting with a single underscore are considered private by convention. Dunder methods (double underscore) like __init__ are not considered private as they are special methods with specific meanings in Python.
- Parameters:
func (nodes.FunctionDef) – Function definition node
- Returns:
True if function name starts with underscore but not double underscore
- Return type:
bool
- pylint_sort_functions.utils.should_function_be_private(func, module_path, project_root, public_patterns=None)
Detect if a function should be private based on import analysis.
Analyzes actual usage patterns across the project to determine if a function is only used within its own module and should therefore be made private.
Detection Logic: 1. Skip if already private (starts with underscore) 2. Skip special methods (__init__, __str__, etc.) 3. Skip configurable public API patterns (main, run, setup, etc.) 4. Check if function is imported/used by other modules 5. If not used externally, suggest making it private
- Parameters:
func (nodes.FunctionDef) – Function definition node to analyze
module_path (Path) – Path to the module file
project_root (Path) – Root directory of the project
public_patterns (set[str] | None) – Set of function names to always treat as public. If None, uses default patterns (main, run, execute, etc.)
- Returns:
True if the function should be marked as private
- Return type:
bool
Plugin Registration
PyLint plugin to enforce alphabetical sorting of functions and methods.
- pylint_sort_functions.register(linter)
Register the plugin with PyLint.
This function is called by PyLint when the plugin is loaded. It registers the FunctionSortChecker with the linter.
Note: This function must remain public as it’s a required PyLint plugin entry point.
- Parameters:
linter (PyLinter) – The PyLint linter instance
- Return type:
None