pypa/pip · error · ClassNotFound

no valid class found in

Error message

no valid {lexername} class found in {filename}

What it means

Raised by load_lexer_from_file() as a ClassNotFound when the file was successfully read and exec'd, but the expected class name (lexername, defaulting to "CustomLexer") is not present in the resulting namespace (line 156-157). It means the file loaded as valid Python but does not define the class you told Pygments to look for.

Solutions

  1. Check the class name defined in your file and pass it explicitly: load_lexer_from_file('mylexer.py', lexername='YourActualClassName').
  2. Ensure the lexer class is defined at module top level (not nested inside a function, conditional, or try/except that swallows it).
  3. Verify the filename argument resolves relative to the current working directory, since load_lexer_from_file resolves it via open(filename) without a search path.

Example fix

// before
load_lexer_from_file('mylexer.py')  # file defines class MyLangLexer

// after
load_lexer_from_file('mylexer.py', lexername='MyLangLexer')
Defensive patterns

Strategy: validation

Validate before calling

import os, ast
def can_load_lexer(filename, lexername='CustomLexer'):
    if not os.path.isfile(filename):
        return False, 'file not found'
    try:
        tree = ast.parse(open(filename, 'rb').read(), filename=filename)
    except SyntaxError as e:
        return False, f'syntax error: {e}'
    names = {n.name for n in ast.walk(tree) if isinstance(n, ast.ClassDef)}
    if lexername not in names:
        return False, f'{lexername} not defined; found {sorted(names)}'
    return True, 'ok'

Type guard

def is_valid_lexer_class(cls) -> bool:
    from pygments.lexer import Lexer
    return isinstance(cls, type) and issubclass(cls, Lexer)

Try / catch

from pygments.util import ClassNotFound
try:
    lexer = load_lexer_from_file(path, lexername=name)
except ClassNotFound as e:
    logger.warning('lexer load failed: %s', e)
    lexer = get_lexer_by_name('text')

Prevention

When it happens

Trigger: Calling load_lexer_from_file('mylexer.py') on a file that defines a class named something other than "CustomLexer" (the default lexername), or calling load_lexer_from_file('mylexer.py', lexername='MyLexer') when the file actually defines a differently-named class. The exec() at line 154 succeeds, but the check `if lexername not in custom_namespace` at line 156 fails.

Common situations: Forgetting to pass the explicit lexername argument when your custom lexer class is not named CustomLexer; refactoring/renaming the lexer class but not the call site; loading a file that defines the class conditionally (e.g., inside an if-block that evaluates false) so it never lands in the top-level namespace.

Related errors


AI-assisted analysis of pypa/pip@f399c37189 (2026-08-08). Data as JSON: /api/errors/44ac1b7e89ae5b7b. Report an issue: GitHub.

Appendix: source

Thrown at src/pip/_vendor/pygments/lexers/__init__.py:157

    directory, which contains a Lexer class. By default, it expects the
    Lexer to be name CustomLexer; you can specify your own class name
    as the second argument to this function.

    Users should be very careful with the input, because this method
    is equivalent to running eval on the input file.

    Raises ClassNotFound if there are any problems importing the Lexer.

    .. versionadded:: 2.2
    """
    try:
        # This empty dict will contain the namespace for the exec'd file
        custom_namespace = {}
        with open(filename, 'rb') as f:
            exec(f.read(), custom_namespace)
        # Retrieve the class `lexername` from that namespace
        if lexername not in custom_namespace:
            raise ClassNotFound(f'no valid {lexername} class found in {filename}')
        lexer_class = custom_namespace[lexername]
        # And finally instantiate it with the options
        return lexer_class(**options)
    except OSError as err:
        raise ClassNotFound(f'cannot read {filename}: {err}')
    except ClassNotFound:
        raise
    except Exception as err:
        raise ClassNotFound(f'error when loading custom lexer: {err}')


def find_lexer_class_for_filename(_fn, code=None):
    """Get a lexer for a filename.

    If multiple lexers match the filename pattern, use ``analyse_text()`` to
    figure out which one is more appropriate.

    Returns None if not found.

View on GitHub (pinned to f399c37189)