{"record":{"id":"477e0585e600b8ba","repo":"pypa/pip","slug":"lex-argument-must-be-a-lexer-instance-not-a-cla","errorCode":null,"errorMessage":"lex() argument must be a lexer instance, not a class","messagePattern":"lex\\(\\) argument must be a lexer instance, not a class","errorType":"validation","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"src/pip/_vendor/pygments/__init__.py","lineNumber":47,"sourceCode":"__version__ = '2.20.0'\n__docformat__ = 'restructuredtext'\n\n__all__ = ['lex', 'format', 'highlight']\n\n\ndef lex(code, lexer):\n    \"\"\"\n    Lex `code` with the `lexer` (must be a `Lexer` instance)\n    and return an iterable of tokens. Currently, this only calls\n    `lexer.get_tokens()`.\n    \"\"\"\n    try:\n        return lexer.get_tokens(code)\n    except TypeError:\n        # Heuristic to catch a common mistake.\n        from pip._vendor.pygments.lexer import RegexLexer\n        if isinstance(lexer, type) and issubclass(lexer, RegexLexer):\n            raise TypeError('lex() argument must be a lexer instance, '\n                            'not a class')\n        raise\n\n\ndef format(tokens, formatter, outfile=None):  # pylint: disable=redefined-builtin\n    \"\"\"\n    Format ``tokens`` (an iterable of tokens) with the formatter ``formatter``\n    (a `Formatter` instance).\n\n    If ``outfile`` is given and a valid file object (an object with a\n    ``write`` method), the result will be written to it, otherwise it\n    is returned as a string.\n    \"\"\"\n    try:\n        if not outfile:\n            realoutfile = getattr(formatter, 'encoding', None) and BytesIO() or StringIO()\n            formatter.format(tokens, realoutfile)\n            return realoutfile.getvalue()","sourceCodeStart":29,"sourceCodeEnd":65,"githubUrl":"https://github.com/pypa/pip/blob/f399c3718970b1b0e2478dac5296eb62679a9b86/src/pip/_vendor/pygments/__init__.py#L29-L65","documentation":"Raised by pygments.lex() when the lexer argument is a RegexLexer *subclass* (a class) rather than an *instance*. lex() tries lexer.get_tokens(code); if that raises TypeError, it checks whether the argument is a class that subclasses RegexLexer and re-raises this clearer message. This is a usability guard against a very common mistake.","triggerScenarios":"Calling pygments.lex(code, PythonLexer) (passing the class) instead of pygments.lex(code, PythonLexer()). The TypeError from calling an unbound method triggers the heuristic at __init__.py:43-49.","commonSituations":"Following an example that forgot to instantiate; copy-paste from docs showing the class name; refactoring from get_lexer_by_name (returns instance) to a direct class reference.","solutions":["Instantiate the lexer class before passing it: lex(code, PythonLexer()).","Use get_lexer_by_name('python') which returns an already-instantiated lexer.","Use the top-level highlight(code, lexer_instance, formatter_instance) helper and ensure all three are instances."],"exampleFix":"# before\nfrom pip._vendor.pygments.lexers import PythonLexer\ntokens = pygments.lex(code, PythonLexer)\n# after\ntokens = pygments.lex(code, PythonLexer())","handlingStrategy":"type-guard","validationCode":"from inspect import isclass\nif isclass(lexer):\n    raise TypeError('pass a lexer instance, not the class')","typeGuard":"def is_lexer_instance(obj) -> bool:\n    from pip._vendor.pygments.lexer import Lexer\n    return isinstance(obj, Lexer)","tryCatchPattern":"try:\n    tokens = pygments.lex(code, lexer)\nexcept TypeError as e:\n    if 'lexer instance' in str(e):\n        lexer = lexer()\n        tokens = pygments.lex(code, lexer)\n    else:\n        raise","preventionTips":["Always instantiate: LexerClass().","Prefer get_lexer_by_name which returns instances."],"tags":["python","pygments","lexer","validation","vendored"],"backgroundTag":null,"analyzedSha":"f399c3718970b1b0e2478dac5296eb62679a9b86","analyzedAt":"2026-08-08T23:01:42.227Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}