CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-pylint

Comprehensive static code analysis tool for Python that performs deep code inspection without executing the program

Pending
Overview
Eval results
Files

configuration.mddocs/

Configuration Management

Hierarchical configuration system that handles command-line arguments, configuration files, and programmatic settings. Pylint's flexible configuration allows customization of analysis behavior, message filtering, and output formatting to match project requirements and coding standards.

Capabilities

Configuration File Discovery

Functions for locating and loading configuration files from multiple sources.

def find_default_config_files():
    """
    Locate default configuration files.
    
    Searches for configuration files in standard locations:
    - Current directory: .pylintrc, pylintrc, pyproject.toml, setup.cfg
    - User home directory: ~/.pylintrc
    - System directories: /etc/pylintrc
    
    Returns:
        list: Paths to found configuration files
    """

def find_pylintrc():
    """
    Find pylintrc configuration file.
    
    Searches in order of precedence:
    1. PYLINTRC environment variable
    2. Current directory .pylintrc
    3. Parent directories (walking up)
    4. User home ~/.pylintrc
    5. System /etc/pylintrc
    
    Returns:
        str: Path to pylintrc file or None
    """

Configuration File Processing

Functions for reading and parsing configuration from various file formats.

def read_config_file(config_file, verbose=False):
    """
    Read configuration from file.
    
    Supports multiple configuration file formats:
    - .pylintrc (INI format)
    - pyproject.toml (TOML format) 
    - setup.cfg (INI format)
    
    Args:
        config_file (str): Path to configuration file
        verbose (bool): Enable verbose output
        
    Returns:
        dict: Parsed configuration options
    """

Arguments Management

Classes for handling command-line arguments and configuration options.

class ArgumentsManager:
    """
    Command-line argument management.
    
    Handles parsing, validation, and processing of command-line
    arguments and configuration file options.
    """
    
    def __init__(self, prog, description):
        """
        Initialize arguments manager.
        
        Args:
            prog (str): Program name
            description (str): Program description
        """
    
    def add_optik_option(self, *args, **kwargs):
        """
        Add command-line option.
        
        Args:
            *args: Option names (e.g., '--disable', '-d')
            **kwargs: Option configuration
        """
    
    def register_options_provider(self, provider, own_group=True):
        """
        Register options provider.
        
        Args:
            provider: Object providing configuration options
            own_group (bool): Create separate option group
        """
    
    def load_config_file(self):
        """Load configuration from file."""
    
    def load_command_line_configuration(self, args=None):
        """
        Load configuration from command line.
        
        Args:
            args (list): Command line arguments
        """

class ArgumentsProvider:
    """
    Base class for configuration providers.
    
    Provides interface for objects that contribute
    configuration options to the argument manager.
    """
    
    name: str  # Provider name
    options: tuple  # Configuration options
    priority: int  # Loading priority
    
    def load_defaults(self):
        """Load default option values."""
    
    def option_value(self, opt):
        """
        Get option value.
        
        Args:
            opt (str): Option name
            
        Returns:
            Option value
        """

Configuration Initialization

Functions for initializing and setting up the complete configuration system.

def _config_initialization(linter, args_list, reporter=None, config_file=None):
    """
    Initialize configuration system.
    
    Handles the complete configuration initialization process:
    1. Load configuration files
    2. Process command-line arguments  
    3. Set up reporters
    4. Validate configuration
    
    Args:
        linter: PyLinter instance
        args_list (list): Command-line arguments
        reporter: Custom reporter instance
        config_file (str): Specific configuration file path
    """

Configuration File Formats

.pylintrc Format

[MAIN]
# Python code to execute, usually for sys.path manipulation
init-hook=

# Files or directories to be skipped
ignore=tests,docs

# Regexp for files/directories to be skipped
ignore-patterns=

# Use multiple processes to speed up Pylint
jobs=1

# List of plugins to load
load-plugins=

# Discover python modules and packages in the file system subtree
recursive=no

[MESSAGES CONTROL]
# Only show warnings with the listed confidence levels
confidence=

# Disable the message, report, category or checker
disable=missing-docstring,
        invalid-name

# Enable the message, report, category or checker  
enable=c-extension-no-member

[REPORTS]
# Set the output format
output-format=text

# Include message's id in output
include-ids=no

# Template for displaying messages
msg-template={path}:{line}: [{msg_id}({symbol}), {obj}] {msg}

# Set the cache size for astroid objects
extension-pkg-whitelist=

[REFACTORING]
# Maximum number of nested blocks for function/method body
max-nested-blocks=5

# Complete name of functions that never returns
never-returning-functions=sys.exit

[BASIC]
# Naming style matching correct argument names
argument-naming-style=snake_case

# Regular expression matching correct argument names
argument-rgx=[a-z_][a-z0-9_]{2,30}$

# Naming style matching correct variable names
variable-naming-style=snake_case

# Good variable names which should always be accepted
good-names=i,j,k,ex,Run,_

# Bad variable names which should always be refused
bad-names=foo,bar,baz,toto,tutu,tata

[FORMAT]
# Maximum number of characters on a single line
max-line-length=100

# Maximum number of lines in a module
max-module-lines=1000

# String used as indentation unit
indent-string='    '

# Expected format of line ending
expected-line-ending-format=

[LOGGING]
# Format style used to check logging format string
logging-format-style=old

# Logging modules to check that the string format arguments are in logging function parameter format
logging-modules=logging

[MISCELLANEOUS]  
# List of note tags to take in consideration
notes=FIXME,XXX,TODO

[SIMILARITIES]
# Minimum lines number of a similarity
min-similarity-lines=4

# Ignore comments when computing similarities
ignore-comments=yes

# Ignore docstrings when computing similarities  
ignore-docstrings=yes

# Ignore imports when computing similarities
ignore-imports=no

[SPELLING]
# Spelling dictionary name
spelling-dict=

# List of comma separated words that should not be checked
spelling-ignore-words=

# A path to a file that contains private dictionary
spelling-private-dict-file=

# Tells whether to store unknown words to indicated private dictionary
spelling-store-unknown-words=no

[TYPECHECK]
# List of decorators that produce context managers
contextmanager-decorators=contextlib.contextmanager

# List of members which are set dynamically and missed by pylint inference system
generated-members=

# Tells whether missing members accessed in mixin class should be ignored
ignore-mixin-members=yes

# List of module names for which member attributes should not be checked
ignored-modules=

# List of class names for which member attributes should not be checked
ignored-classes=optparse.Values,thread._local,_thread._local

# List of classes names for which member attributes should not be checked
ignored-classes=optparse.Values,thread._local,_thread._local

[VARIABLES]
# List of additional names supposed to be defined in builtins
additional-builtins=

# Tells whether unused global variables should be treated as a violation
allow-global-unused-variables=yes

# List of strings which can identify a callback function by name
callbacks=cb_,_cb

# A regular expression matching the name of dummy variables
dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_

# Argument names that match this expression will be ignored
ignored-argument-names=_.*|^ignored_|^unused_

# Tells whether we should check for unused import in __init__ files
init-import=no

# List of qualified module names which can have objects that can redefine builtins
redefining-builtins-modules=six.moves,past.builtins,future.builtins,builtins,io

[CLASSES]
# List of method names used to declare (i.e. assign) instance attributes
defining-attr-methods=__init__,__new__,setUp,__post_init__

# List of member names, which should be excluded from the protected access warning
exclude-protected=_asdict,_fields,_replace,_source,_make

# List of valid names for the first argument in a class method
valid-classmethod-first-arg=cls

# List of valid names for the first argument in a metaclass class method
valid-metaclass-classmethod-first-arg=cls

[DESIGN]
# Maximum number of arguments for function/method
max-args=5

# Maximum number of attributes for a class
max-attributes=7

# Maximum number of boolean expressions in an if statement
max-bool-expr=5

# Maximum number of branch for function/method body
max-branches=12

# Maximum number of locals for function/method body
max-locals=15

# Maximum number of parents for a class
max-parents=7

# Maximum number of public methods for a class
max-public-methods=20

# Maximum number of return/yield for function/method body
max-returns=6

# Maximum number of statements in function/method body
max-statements=50

# Minimum number of public methods for a class
min-public-methods=2

[IMPORTS]
# List of modules that can be imported at any level, not just the top level
allow-any-import-level=

# Allow wildcard imports from modules that define __all__
allow-wildcard-with-all=no

# Analyse import fallback blocks
analyse-fallback-blocks=no

# Deprecated modules which should not be used
deprecated-modules=optparse,tkinter.tix

# Create a graph of external dependencies in the given file
ext-import-graph=

# Create a graph of every (i.e. internal and external) dependencies in the given file
import-graph=

# Create a graph of internal dependencies in the given file  
int-import-graph=

# Force import order to recognize a module as part of the standard compatibility libraries
known-standard-library=

# Force import order to recognize a module as part of a third party library
known-third-party=enchant

# Couples of modules and preferred modules
preferred-modules=

[EXCEPTIONS]
# Exceptions that will emit a warning when being caught
overgeneral-exceptions=BaseException,Exception

pyproject.toml Format

[tool.pylint.main]
# Files or directories to be skipped
ignore = ["tests", "docs"]

# Use multiple processes to speed up Pylint  
jobs = 0

# List of plugins to load
load-plugins = [
    "pylint.extensions.docparams",
    "pylint.extensions.mccabe"
]

[tool.pylint.messages_control]
# Disable the message, report, category or checker
disable = [
    "missing-docstring",
    "invalid-name",
    "too-few-public-methods"
]

[tool.pylint.format]
# Maximum number of characters on a single line
max-line-length = 100

[tool.pylint.basic]
# Good variable names which should always be accepted
good-names = ["i", "j", "k", "ex", "Run", "_"]

[tool.pylint.design]
# Maximum number of arguments for function/method
max-args = 5

# Maximum number of locals for function/method body
max-locals = 15

Programmatic Configuration

Using PyLinter Configuration

from pylint.lint import PyLinter

# Create linter instance
linter = PyLinter()

# Set basic options
linter.config.disable = ['missing-docstring', 'invalid-name']
linter.config.max_line_length = 120
linter.config.good_names = ['i', 'j', 'k', 'x', 'y', 'z']

# Configure reports
linter.config.reports = True
linter.config.score = True
linter.config.msg_template = '{path}:{line}: {msg_id}: {msg}'

# Configure analysis behavior
linter.config.recursive = True
linter.config.jobs = 4
linter.config.suggestion_mode = True

Dynamic Configuration Loading

from pylint.config import find_pylintrc, read_config_file

# Find configuration file
config_file = find_pylintrc()
if config_file:
    # Load configuration
    config = read_config_file(config_file, verbose=True)
    
    # Apply to linter
    linter = PyLinter()
    linter.load_config_file(config_file)

Custom Configuration Provider

from pylint.config import ArgumentsProvider

class CustomConfigProvider(ArgumentsProvider):
    """Custom configuration provider."""
    
    name = 'custom'
    priority = 1
    
    options = (
        ('custom-option', {
            'default': True,
            'type': 'yn',
            'help': 'Enable custom behavior'
        }),
        ('custom-threshold', {
            'default': 10,
            'type': 'int',
            'help': 'Custom threshold value'
        })
    )
    
    def load_defaults(self):
        """Load default values."""
        for option_name, option_dict in self.options:
            setattr(self.config, option_name.replace('-', '_'), 
                   option_dict['default'])

# Register with linter
linter = PyLinter()
provider = CustomConfigProvider()
linter.register_options_provider(provider)

Environment Variables

Configuration Environment Variables

# Specify configuration file
export PYLINTRC=/path/to/custom/pylintrc

# Set default options
export PYLINT_DISABLE=missing-docstring,invalid-name
export PYLINT_JOBS=4

# Plugin loading
export PYLINT_LOAD_PLUGINS=mccabe,docparams

Usage in Scripts

import os
from pylint.lint import PyLinter

# Check environment variables
config_file = os.environ.get('PYLINTRC')
jobs = int(os.environ.get('PYLINT_JOBS', '1'))
disabled = os.environ.get('PYLINT_DISABLE', '').split(',')

linter = PyLinter()
if config_file:
    linter.load_config_file(config_file)

linter.config.jobs = jobs
if disabled and disabled[0]:  # Check if not empty
    linter.config.disable.extend(disabled)

Configuration Best Practices

Project-Specific Configuration

# Create project-specific .pylintrc
def create_project_config():
    config_content = """
[MAIN]
init-hook='import sys; sys.path.append("src")'
load-plugins=pylint.extensions.mccabe

[MESSAGES CONTROL]  
disable=missing-docstring,
        invalid-name,
        too-few-public-methods

[FORMAT]
max-line-length=100
indent-string='    '

[DESIGN]
max-args=7
max-locals=20
max-complexity=10
"""
    
    with open('.pylintrc', 'w') as f:
        f.write(config_content.strip())

# Use in CI/CD
def setup_ci_config():
    linter = PyLinter()
    
    # Strict settings for CI
    linter.config.fail_under = 8.0  # Minimum score
    linter.config.disable = ['locally-disabled']  # No local disables
    linter.config.output_format = 'json'  # Machine readable
    
    return linter

Install with Tessl CLI

npx tessl i tessl/pypi-pylint

docs

built-in-checkers.md

checker-development.md

configuration.md

core-linting.md

extensions.md

index.md

messages.md

pyreverse.md

reporters.md

test-utilities.md

tile.json