pypa/pip · error · ClassNotFound

error when loading custom formatter

Error message

error when loading custom formatter: {err}

What it means

Raised by load_formatter_from_file for any Exception during exec() of the file other than OSError or an explicit ClassNotFound. This catches SyntaxError, import errors, instantiation errors, or exceptions thrown while the formatter class is being instantiated. The original exception message is folded into the ClassNotFound message at __init__.py:114-115.

Solutions

  1. Import the file standalone (python -c "exec(open('myfmt.py').read())") to see the real underlying exception.
  2. Install any missing dependencies the formatter imports.
  3. Fix syntax errors in the file.
  4. Ensure the options passed match what the formatter's __init__ expects.

Example fix

# diagnose the hidden error
import traceback
try:
    load_formatter_from_file('myfmt.py')
except Exception:
    traceback.print_exc()
# then fix the root cause (e.g. add missing import) in myfmt.py
Defensive patterns

Strategy: try-catch

Validate before calling

null

Type guard

null

Try / catch

from pip._vendor.pygments.util import ClassNotFound
try:
    fmt = load_formatter_from_file(path)
except ClassNotFound as e:
    # surface the wrapped message to debug the real cause
    import logging; logging.exception('formatter load failed')
    raise

Prevention

When it happens

Trigger: The custom formatter file has a SyntaxError, raises ImportError (missing dependency), references undefined names, or its __init__ raises an error during formatter_class(**options).

Common situations: Formatter depends on a package not installed in the environment; Python 2 vs 3 syntax; class __init__ rejects the options dict; typo in an attribute reference inside the file.

Related errors


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

Appendix: source

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

    .. 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.
    """
    fn = basename(fn)
    for modname, name, _, filenames, _ in FORMATTERS.values():
        for filename in filenames:
            if _fn_matches(fn, filename):
                if name not in _formatter_cache:
                    _load_formatters(modname)
                return _formatter_cache[name](**options)
    for _name, cls in find_plugin_formatters():

View on GitHub (pinned to f399c37189)