{"id":"71568a4732b316e6","repo":"pypa/pip","slug":"error-when-loading-custom-formatter-err","errorCode":null,"errorMessage":"error when loading custom formatter: {err}","messagePattern":"error when loading custom formatter: (.+?)","errorType":"exception","errorClass":"ClassNotFound","httpStatus":null,"severity":"error","filePath":"src/pip/_vendor/pygments/formatters/__init__.py","lineNumber":115,"sourceCode":"    .. versionadded:: 2.2\n    \"\"\"\n    try:\n        # This empty dict will contain the namespace for the exec'd file\n        custom_namespace = {}\n        with open(filename, 'rb') as f:\n            exec(f.read(), custom_namespace)\n        # Retrieve the class `formattername` from that namespace\n        if formattername not in custom_namespace:\n            raise ClassNotFound(f'no valid {formattername} class found in {filename}')\n        formatter_class = custom_namespace[formattername]\n        # And finally instantiate it with the options\n        return formatter_class(**options)\n    except OSError as err:\n        raise ClassNotFound(f'cannot read {filename}: {err}')\n    except ClassNotFound:\n        raise\n    except Exception as err:\n        raise ClassNotFound(f'error when loading custom formatter: {err}')\n\n\ndef get_formatter_for_filename(fn, **options):\n    \"\"\"\n    Return a :class:`.Formatter` subclass instance that has a filename pattern\n    matching `fn`. The formatter is given the `options` at its instantiation.\n\n    Will raise :exc:`pygments.util.ClassNotFound` if no formatter for that filename\n    is found.\n    \"\"\"\n    fn = basename(fn)\n    for modname, name, _, filenames, _ in FORMATTERS.values():\n        for filename in filenames:\n            if _fn_matches(fn, filename):\n                if name not in _formatter_cache:\n                    _load_formatters(modname)\n                return _formatter_cache[name](**options)\n    for _name, cls in find_plugin_formatters():","sourceCodeStart":97,"sourceCodeEnd":133,"githubUrl":"https://github.com/pypa/pip/blob/d7d0d0a39494e28ec1c407bd0680e4a4d1067791/src/pip/_vendor/pygments/formatters/__init__.py#L97-L133","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","solutions":["Run the file standalone (python -m py_compile myfmt.py or python myfmt.py) to surface the real error.","Fix the syntax/import/runtime error the embedded message reports.","Ensure all imports the file needs are installed in the environment."],"exampleFix":"# before: myfmt.py has `from missing_pkg import X`\n# run to diagnose:\n#   python myfmt.py   -> ModuleNotFoundError: No module named 'missing_pkg'\n# after: install missing_pkg or remove the import","handlingStrategy":"try-catch","validationCode":"import py_compile\ndef compiles_clean(filename):\n    try:\n        py_compile.compile(filename, doraise=True)\n        return True\n    except py_compile.PyCompileError:\n        return False","typeGuard":null,"tryCatchPattern":"from pygments.util import ClassNotFound\ntry:\n    fmt = load_formatter_from_file(fn, name)\nexcept ClassNotFound as e:\n    if 'error when loading' in str(e):\n        log.error('custom formatter failed: %s', e)\n        fmt = get_formatter_by_name('html')\n    else:\n        raise","preventionTips":["Byte-compile the file before passing it to load_formatter_from_file.","Keep custom formatter dependencies minimal and installed."],"tags":["pygments","formatter","custom","dynamic-load"],"analyzedSha":"d7d0d0a39494e28ec1c407bd0680e4a4d1067791","analyzedAt":"2026-08-04T20:55:04.259Z","schemaVersion":2}