pypa/pip · error · ClassNotFound

no valid class found in

Error message

no valid {formattername} class found in {filename}

What it means

Raised by load_formatter_from_file when the exec'd file does not define the expected class name (default 'CustomFormatter') in its namespace. The file was read and executed successfully, but no attribute with formattername exists, so ClassNotFound is raised at __init__.py:105-106. This is a content mismatch, not an I/O or syntax error.

Solutions

  1. Name the formatter class CustomFormatter in the file, or pass the correct name: load_formatter_from_file('myfmt.py', 'MyFormatter').
  2. Ensure the class is defined at module top level (not inside an if/try that doesn't run).
  3. Verify the file's contents actually define the class with no import errors.

Example fix

# before
# myfmt.py defines class MyFormatter(Formatter)
load_formatter_from_file('myfmt.py')
# after
load_formatter_from_file('myfmt.py', 'MyFormatter')
Defensive patterns

Strategy: validation

Validate before calling

import os
ns = {}
with open(path, 'rb') as fh:
    exec(fh.read(), ns)
if class_name not in ns:
    raise ValueError(f'{class_name} not defined in {path}')

Type guard

def file_defines_class(path: str, class_name: str) -> bool:
    import os
    if not os.path.isfile(path):
        return False
    ns = {}
    with open(path, 'rb') as fh:
        exec(fh.read(), ns)
    return class_name in ns

Try / catch

from pip._vendor.pygments.util import ClassNotFound
try:
    fmt = load_formatter_from_file(path, name)
except ClassNotFound as e:
    if 'no valid' in str(e):
        name = 'CustomFormatter'
        fmt = load_formatter_from_file(path, name)
    else:
        raise

Prevention

When it happens

Trigger: Calling load_formatter_from_file('myfmt.py') when the file defines class MyFormatter but the function looks for CustomFormatter; or passing a wrong formattername argument.

Common situations: Forgot to name the class CustomFormatter; mismatched class name between the file and the formattername argument; class defined under a conditional that was False so it never entered the namespace.

Related errors


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

Appendix: source

Thrown at src/pip/_vendor/pygments/formatters/__init__.py:106

    The file is expected to contain a Formatter class named ``formattername``
    (by default, CustomFormatter). Users should be very careful with the input, because
    this method is equivalent to running ``eval()`` on the input file. The formatter is
    given the `options` at its instantiation.

    :exc:`pygments.util.ClassNotFound` is raised if there are any errors loading
    the formatter.

    .. 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 `formattername` from that namespace
        if formattername not in custom_namespace:
            raise ClassNotFound(f'no valid {formattername} class found in {filename}')
        formatter_class = custom_namespace[formattername]
        # And finally instantiate it with the options
        return formatter_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 formatter: {err}')


def get_formatter_for_filename(fn, **options):
    """
    Return a :class:`.Formatter` subclass instance that has a filename pattern
    matching `fn`. The formatter is given the `options` at its instantiation.

    Will raise :exc:`pygments.util.ClassNotFound` if no formatter for that filename
    is found.

View on GitHub (pinned to f399c37189)