or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/pypi-pep8-naming

A flake8 plugin that enforces PEP 8 naming conventions in Python code

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/pep8-naming@0.15.x

To install, run

npx @tessl/cli install tessl/pypi-pep8-naming@0.15.0

index.mddocs/

pep8-naming

A flake8 plugin that enforces PEP 8 naming conventions in Python code. The plugin automatically detects various naming violations including improper class names, function names, variable names, constant names, and import naming issues. It integrates seamlessly with flake8's existing workflow and provides configurable options for customizing behavior.

Package Information

  • Package Name: pep8-naming
  • Language: Python
  • Installation: pip install pep8-naming
  • Requirements: Python ≥3.9, flake8 ≥5.0.0

Core Imports

The plugin is automatically loaded by flake8 when both packages are installed:

# The plugin is used through flake8, not directly imported
# But if you need to use components programmatically:
from pep8ext_naming import NamingChecker, BaseASTCheck, FunctionType, NameSet
from pep8ext_naming import ClassNameCheck, FunctionNameCheck, FunctionArgNamesCheck
from pep8ext_naming import ImportAsCheck, VariablesCheck, TypeVarNameCheck
from pep8ext_naming import is_mixed_case, _extract_names, _build_decorator_to_type

# For working with AST nodes:
import ast
from collections import deque
from collections.abc import Sequence, Iterator

Basic Usage

The plugin is used through flake8's command line interface:

# Install both flake8 and pep8-naming
pip install flake8 pep8-naming

# Run flake8 on your code - the naming plugin is automatically enabled
flake8 myproject/

# Check specific files
flake8 myfile.py

# Use configuration options
flake8 --ignore-names="setUp,tearDown" --classmethod-decorators="classmethod,declared_attr" myproject/

Configuration can also be placed in setup.cfg, tox.ini, or .flake8:

[flake8]
ignore-names = setUp,tearDown,setUpClass,tearDownClass
classmethod-decorators = classmethod,declared_attr
staticmethod-decorators = staticmethod

Architecture

The plugin uses flake8's AST visitor pattern with the following key components:

  • NamingChecker: Main plugin class that coordinates all checks and integrates with flake8
  • BaseASTCheck: Abstract base class for all naming checks with error reporting functionality
  • Checker Classes: Specialized classes for different types of naming violations (ClassNameCheck, FunctionNameCheck, etc.)
  • Configuration System: Flexible options for customizing ignored names and decorator recognition

Capabilities

Main Plugin Interface

The primary interface for flake8 integration, providing all configuration options and error detection coordination.

class NamingChecker:
    """Main flake8 plugin checker for PEP-8 naming conventions."""
    name = 'naming'
    version = '0.15.1'
    
    def __init__(self, tree, filename):
        """Initialize checker with AST tree and filename."""
    
    @classmethod
    def add_options(cls, parser):
        """Add command-line options to flake8 parser."""
    
    @classmethod  
    def parse_options(cls, options):
        """Parse and store configuration from flake8 options."""
    
    def run(self):
        """Run all checks and yield violations as (line, col, message, type) tuples."""
    
    def visit_tree(self, node, parents):
        """
        Recursively visit AST tree nodes and yield violations.
        
        Args:
            node: AST node to visit
            parents: deque of parent nodes for context
            
        Yields:
            Tuples of (line, col, message, checker) for each violation found
        """
    
    def visit_node(self, node, parents):
        """
        Visit individual AST node and call appropriate visitor methods.
        
        Args:
            node: AST node to process
            parents: Sequence of parent nodes for context
            
        Yields:
            Tuples of (line, col, message, checker) for each violation found
        """
    
    def tag_class_functions(self, cls_node):
        """
        Tag functions if they are methods, classmethods, staticmethods.
        
        Args:
            cls_node: ast.ClassDef node to analyze
        """
    
    def set_function_nodes_types(self, nodes, ismetaclass, late_decoration):
        """
        Set function_type attributes on AST function nodes.
        
        Args:
            nodes: Iterator of AST nodes to process
            ismetaclass: Whether the containing class is a metaclass
            late_decoration: Dict mapping function names to decorator types
        """
    
    @classmethod
    def find_decorator_name(cls, d):
        """
        Extract decorator name from AST decorator node.
        
        Args:
            d: AST decorator node (ast.Name, ast.Attribute, or ast.Call)
            
        Returns:
            Decorator name as string, or None if not found
        """
    
    @staticmethod
    def find_global_defs(func_def_node):
        """
        Find global variable declarations within function.
        
        Args:
            func_def_node: ast.FunctionDef or ast.AsyncFunctionDef node
        """

Check Base Classes

Foundation classes for implementing naming convention checks.

class BaseASTCheck:
    """Base class for AST-based naming checks."""
    all = []  # Registry of all check instances
    codes = ()  # Error codes handled by this checker
    
    def err(self, node, code, **kwargs):
        """Create error tuple for a naming violation."""

class NameSet(frozenset):
    """Set of names supporting Unix shell-style wildcard matching."""
    
    def __new__(cls, iterable):
        """Create NameSet with wildcard pattern detection."""
    
    def __contains__(self, item):
        """Check membership with wildcard pattern matching support."""

Function Type Classification

Enumeration and utilities for classifying different types of functions and methods.

class FunctionType(enum.Enum):
    """Enumeration of function/method types for naming checks."""
    CLASSMETHOD = 'classmethod'
    STATICMETHOD = 'staticmethod' 
    FUNCTION = 'function'
    METHOD = 'method'

Naming Check Classes

Specialized checker classes that implement specific naming convention rules.

class ClassNameCheck(BaseASTCheck):
    """Checks class names use CapWords convention and exception names end with Error."""
    N801 = "class name '{name}' should use CapWords convention"
    N818 = "exception name '{name}' should be named with an Error suffix"
    
    def visit_classdef(self, node, parents, ignored):
        """Check class definition for naming violations."""
    
    @classmethod
    def get_classdef(cls, name, parents):
        """Find class definition by name in parent nodes."""
    
    @classmethod  
    def superclass_names(cls, name, parents, _names=None):
        """Get names of all superclasses for inheritance checks."""

class FunctionNameCheck(BaseASTCheck):
    """Checks function names are lowercase and don't use double underscores improperly."""
    N802 = "function name '{name}' should be lowercase"
    N807 = "function name '{name}' should not start and end with '__'"
    
    def visit_functiondef(self, node, parents, ignored):
        """Check function definition for naming violations."""
    
    visit_asyncfunctiondef = visit_functiondef  # Alias for async functions
    
    @staticmethod
    def has_override_decorator(node):
        """Check if function has typing.override decorator."""

class FunctionArgNamesCheck(BaseASTCheck):
    """Checks function argument names are lowercase and first arguments are 'self'/'cls' appropriately."""
    N803 = "argument name '{name}' should be lowercase"
    N804 = "first argument of a classmethod should be named 'cls'"
    N805 = "first argument of a method should be named 'self'"
    
    def visit_functiondef(self, node, parents, ignored):
        """Check function arguments for naming violations."""
    
    visit_asyncfunctiondef = visit_functiondef  # Alias for async functions

class ImportAsCheck(BaseASTCheck):
    """Checks import aliases maintain original naming conventions."""
    N811 = "constant '{name}' imported as non constant '{asname}'"
    N812 = "lowercase '{name}' imported as non lowercase '{asname}'"
    N813 = "camelcase '{name}' imported as lowercase '{asname}'"
    N814 = "camelcase '{name}' imported as constant '{asname}'"
    N817 = "camelcase '{name}' imported as acronym '{asname}'"
    
    def visit_importfrom(self, node, parents, ignored):
        """Check from-import aliases for naming violations."""
    
    visit_import = visit_importfrom  # Alias for regular imports

class VariablesCheck(BaseASTCheck):
    """Checks variable names in different scopes follow appropriate conventions."""
    N806 = "variable '{name}' in function should be lowercase"
    N815 = "variable '{name}' in class scope should not be mixedCase"
    N816 = "variable '{name}' in global scope should not be mixedCase"
    
    def visit_assign(self, node, parents, ignored):
        """Check assignment targets for naming violations."""
    
    def visit_namedexpr(self, node, parents, ignored):
        """Check walrus operator targets for naming violations."""
    
    visit_annassign = visit_namedexpr  # Alias for annotated assignments
    
    def visit_with(self, node, parents, ignored):
        """Check with statement targets for naming violations."""
    
    visit_asyncwith = visit_with  # Alias for async with statements
    
    def visit_for(self, node, parents, ignored):
        """Check for loop targets for naming violations."""
    
    visit_asyncfor = visit_for  # Alias for async for loops
    
    def visit_excepthandler(self, node, parents, ignored):
        """Check exception handler names for naming violations."""
    
    def visit_generatorexp(self, node, parents, ignored):
        """Check generator expression targets for naming violations."""
    
    visit_listcomp = visit_dictcomp = visit_setcomp = visit_generatorexp  # Aliases for comprehensions
    
    @staticmethod
    def global_variable_check(name):
        """Check global variable name, return error code if invalid."""
    
    @staticmethod
    def class_variable_check(name):
        """Check class variable name, return error code if invalid."""
    
    @staticmethod
    def function_variable_check(func, var_name):
        """Check function variable name, return error code if invalid."""
    
    @staticmethod
    def is_namedtupe(node_value):
        """Check if assignment value is a namedtuple call."""
    
    def _find_errors(self, assignment_target, parents, ignored):
        """
        Find naming errors in assignment targets.
        
        Args:
            assignment_target: AST node representing assignment target
            parents: Sequence of parent nodes for context
            ignored: NameSet of names to ignore
            
        Yields:
            Error tuples for naming violations found
        """

class TypeVarNameCheck(BaseASTCheck):
    """Checks TypeVar names use CapWords convention with optional covariance/contravariance suffixes."""
    N808 = "type variable name '{name}' should use CapWords convention and an optional '_co' or '_contra' suffix"
    
    def visit_module(self, node, parents, ignored):
        """Check module-level TypeVar assignments for naming violations."""

Utility Functions

Helper functions used throughout the naming checks.

def is_mixed_case(name):
    """
    Check if name uses mixedCase (starts lowercase, contains uppercase).
    
    Args:
        name: Variable name to check
    
    Returns:
        True if name is in mixedCase format
    """

def _extract_names(assignment_target):
    """
    Extract all variable names from assignment target.
    
    Args:
        assignment_target: AST node representing assignment target
    
    Yields:
        Variable names found in the assignment target
    """

def _build_decorator_to_type(classmethod_decorators, staticmethod_decorators):
    """
    Build mapping from decorator names to function types.
    
    Args:
        classmethod_decorators: List of classmethod decorator names
        staticmethod_decorators: List of staticmethod decorator names
    
    Returns:
        Dictionary mapping decorator names to FunctionType values
    """

Configuration Constants

Default values and constants used for configuration.

__version__ = '0.15.1'

CLASS_METHODS = frozenset([
    '__new__', '__init_subclass__', '__class_getitem__'
])

METACLASS_BASES = frozenset(['type', 'ABCMeta'])

METHOD_CONTAINER_NODES = {
    ast.If, ast.While, ast.For, ast.With, ast.Try, ast.AsyncWith, ast.AsyncFor
}

FUNC_NODES = (ast.FunctionDef, ast.AsyncFunctionDef)

_default_ignored_names = [
    'setUp', 'tearDown', 'setUpClass', 'tearDownClass', 
    'setUpModule', 'tearDownModule', 'asyncSetUp', 'asyncTearDown',
    'setUpTestData', 'failureException', 'longMessage', 'maxDiff'
]

_default_classmethod_decorators = ['classmethod']
_default_staticmethod_decorators = ['staticmethod']

Error Codes

The plugin detects the following PEP 8 naming violations:

CodeDescription
N801Class names should use CapWords convention
N802Function name should be lowercase
N803Argument name should be lowercase
N804First argument of a classmethod should be named 'cls'
N805First argument of a method should be named 'self'
N806Variable in function should be lowercase
N807Function name should not start and end with '__'
N808Type variable names should use CapWords with optional '_co'/'_contra' suffix
N811Constant imported as non-constant
N812Lowercase imported as non-lowercase
N813Camelcase imported as lowercase
N814Camelcase imported as constant
N815MixedCase variable in class scope
N816MixedCase variable in global scope
N817Camelcase imported as acronym
N818Exception name should be named with an Error suffix

Configuration Options

The plugin supports the following flake8 configuration options:

  • --ignore-names: Comma-separated list of names or glob patterns to ignore
  • --classmethod-decorators: List of decorators to treat as classmethods (default: classmethod)
  • --staticmethod-decorators: List of decorators to treat as staticmethods (default: staticmethod)

Example configuration in setup.cfg:

[flake8]
ignore-names = setUp,tearDown,*Test*
classmethod-decorators = classmethod,declared_attr,expression,comparator
staticmethod-decorators = staticmethod