{"record":{"id":"30661ffcce68335b","repo":"pypa/pip","slug":"error-when-loading-custom-lexer-err","errorCode":null,"errorMessage":"error when loading custom lexer: {err}","messagePattern":"error when loading custom lexer: (.+?)","errorType":"exception","errorClass":"ClassNotFound","httpStatus":null,"severity":"error","filePath":"src/pip/_vendor/pygments/lexers/__init__.py","lineNumber":166,"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 `lexername` from that namespace\n        if lexername not in custom_namespace:\n            raise ClassNotFound(f'no valid {lexername} class found in {filename}')\n        lexer_class = custom_namespace[lexername]\n        # And finally instantiate it with the options\n        return lexer_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 lexer: {err}')\n\n\ndef find_lexer_class_for_filename(_fn, code=None):\n    \"\"\"Get a lexer for a filename.\n\n    If multiple lexers match the filename pattern, use ``analyse_text()`` to\n    figure out which one is more appropriate.\n\n    Returns None if not found.\n    \"\"\"\n    matches = []\n    fn = basename(_fn)\n    for modname, name, _, filenames, _ in LEXERS.values():\n        for filename in filenames:\n            if _fn_matches(fn, filename):\n                if name not in _lexer_cache:\n                    _load_lexers(modname)\n                matches.append((_lexer_cache[name], filename))","sourceCodeStart":148,"sourceCodeEnd":184,"githubUrl":"https://github.com/pypa/pip/blob/f399c3718970b1b0e2478dac5296eb62679a9b86/src/pip/_vendor/pygments/lexers/__init__.py#L148-L184","documentation":"Raised by load_lexer_from_file() as a ClassNotFound when exec(f.read(), custom_namespace) at line 154, or the subsequent instantiation at line 160, raises any exception that is not OSError or ClassNotFound — caught by the generic `except Exception as err` at line 165-166. The inner error is stringified into the message.","triggerScenarios":"The loaded file contains a Python SyntaxError, ImportError, or NameError; the file defines the class but the class's __init__ or a module-level statement raises during exec; the retrieved class is not callable or fails at lexer_class(**options).","commonSituations":"The custom lexer file imports another module that is not installed in the environment; the file has an unguarded import that fails at exec time; the lexer class constructor requires arguments not supplied via options; a typo/indentation error in the file.","solutions":["Open and inspect the inner error in the message — it includes the original exception text (e.g., ImportError: No module named 'foo').","Import and exec the file yourself in a REPL to reproduce the underlying exception with a full traceback before the ClassNotFound wrapper hides it.","Ensure all dependencies the custom lexer file imports are installed and that the file is syntactically valid (python -m py_compile yourfile.py)."],"exampleFix":"// before\nlexer = load_lexer_from_file('mylexer.py')  # raises \"error when loading custom lexer: ImportError ...\"\n\n// after\n# reproduce raw error first to see full traceback\nimport ast; ast.parse(open('mylexer.py','rb').read())\n# then fix the missing dependency / syntax in mylexer.py\nlexer = load_lexer_from_file('mylexer.py')","handlingStrategy":"try-catch","validationCode":"import ast\ndef file_parses(filename):\n    try:\n        ast.parse(open(filename, 'rb').read(), filename=filename)\n        return True\n    except SyntaxError:\n        return False","typeGuard":null,"tryCatchPattern":"from pygments.util import ClassNotFound\ntry:\n    lexer = load_lexer_from_file(path, lexername=name)\nexcept ClassNotFound as e:\n    # 'error when loading custom lexer: <inner>' — surface inner cause\n    raise RuntimeError(f'custom lexer load failed: {e}') from e","preventionTips":["Run python -m py_compile on the lexer file before loading to catch syntax errors early.","Ensure every import inside the custom lexer file is satisfiable in the target environment.","Reproduce the exec() in a REPL to see the unwrapped traceback before relying on the wrapped message."],"tags":["pygments","lexer","custom-lexer","exec-error"],"backgroundTag":null,"analyzedSha":"f399c3718970b1b0e2478dac5296eb62679a9b86","analyzedAt":"2026-08-08T23:01:42.227Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}