pypa/pip · error · ClassNotFound

error when loading custom formatter: {err}

Error message

error when loading custom formatter: {err}

What it means

Raised by load_formatter_from_file as a catch-all when exec() of the file raises any exception other than OSError or ClassNotFound (SyntaxError, ImportError, NameError, etc.). The original exception text is embedded in the message.

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 d7d0d0a394)

Solutions

  1. Run the file standalone (python -m py_compile myfmt.py or python myfmt.py) to surface the real error.
  2. Fix the syntax/import/runtime error the embedded message reports.
  3. Ensure all imports the file needs are installed in the environment.

Example fix

# before: myfmt.py has `from missing_pkg import X`
# run to diagnose:
#   python myfmt.py   -> ModuleNotFoundError: No module named 'missing_pkg'
# after: install missing_pkg or remove the import
Defensive patterns

Strategy: try-catch

Validate before calling

import py_compile
def compiles_clean(filename):
    try:
        py_compile.compile(filename, doraise=True)
        return True
    except py_compile.PyCompileError:
        return False

Try / catch

from pygments.util import ClassNotFound
try:
    fmt = load_formatter_from_file(fn, name)
except ClassNotFound as e:
    if 'error when loading' in str(e):
        log.error('custom formatter failed: %s', e)
        fmt = get_formatter_by_name('html')
    else:
        raise

Prevention

When it happens

Trigger: The custom formatter file contains a syntax error, references an undefined name, or fails an import at module level; any exception during class body execution.

Common situations: Editing the formatter file and introducing a typo; depending on a third-party import inside the formatter file that isn't installed; Python version incompatibility in the file.

Related errors


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