You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Make Lexer::current_range and Lexer::current_flags public? #28415
I'm exploring ways to improve the performance of Griffe, a static analysis tool written in Python. Its current bottleneck is compile(), used to build ASTs from source code.
I'm using Ruff's parser, and more specifically its lexer, to prune the body of functions in source code before passing it to compile: I don't ever visit these bodies so I can simply "hide" them when building the AST. That gives a speedup of about 3x for building ASTs on libraries like mypy or Pydantic (that of course depends on the input files).
The thing is, I currently have to vendor ruff_python_parser to make Lexer::current_range and Lexer::current_flags public, in order to be able to replace function bodies with blank lines.
Would you consider making these two symbols public? If not, I'm happy to keep vendoring it, it won't need frequent updates 🙂
Alternatively, do you have any recommendations on how to achieve what I'm doing without relying on these two symbols? Or, maybe do you have general advice on how to make Python's compile() faster ☺️?
How do you detect a function body? Do you match based on seeing the first indent after a def keyword?
In general, our lexer is not intended to be consumed directly. Unlike a lexer described in a classical compiler book, our lexer depends on a feedback loop with the parser to distinguish whether a contextual keywords is a keyword or a name in the current context (relevant for handling match and case). I don't think this matters to you but we may use this mechanism for other language features in the future if necessary. Because of that, I mainly consider our lexer as internal. The only reason lex is public is because it is required for benchmarking 😅
Having said all this. I don't mind it terribly to make these methods public. Although I'm not sure why you'd need current_flags and I also can't guarantee that these methods will remain public or remain existing in the future.
If you want to build on slightly more stable API, I'd suggest you to parse the AST, and take the range from the body's first and last statement. Unfortunately, this is likely to be a good deal slower than just lexing because Ruff has to allocate an AST. But I'm not sure if the difference is notable for your use case (it's still pretty fast) and it's likely also more resilient than guessing function bodies from the token stream.
The other alternative is that you simply copy the entire lexer module. It isn't that much code.
How do you detect a function body? Do you match based on seeing the first indent after a def keyword?
The pruner uses Ruff’s lexer tokens:
A Def token starts a function header.
It finds the header’s terminating : only after the parameter list has closed, accounting for multiline signatures, nested delimiters, and lambda colons in return annotations.
After ::
A logical newline followed by Indent starts an indented body.
Any other meaningful token starts a same-line body, such as def f(): return 1.
An indented body ends when Ruff emits a Dedent returning below that body’s recorded indentation depth. An inline body ends at the logical Newline.
If there's a multiline string (triple quoted string) in the middle of the function body, that still works because the string is parsed as a single String token.
If you want to build on slightly more stable API, I'd suggest you to parse the AST, and take the range from the body's first and last statement.
Oh, right, that's exactly what I was doing before that, but it felt wasteful to lex+parse in Rust, then tokenize+parse again in Python through compile(). It felt wasteful but it was already a performance improvement. I simply wanted to try and push it even further to maximize the performance gains (to compensate the added but well hidden complexity).
Oh and the pruner uses the flags only to distinguish between "real docstring" and b"not a docstring" (Python doesn't consider byte strings as docstrings). Arguably this is an edge-case and we probably do not need it, but everything can be found in the wild so better be safe.
Having said all this. I don't mind it terribly to make these methods public. [...] I also can't guarantee that these methods will remain public or remain existing in the future.
That'd be perfectly fine to me, I don't mind if API stability isn't guaranteed. It will already be super helpful because that means I don't have to vendor the code (keeping it up to date, while patching the two symbols everytime I update, etc.). But again, no worries if you don't think it's worth it, it's totally manageable on my end.
I see. I'm okay making these methods pub (but maybe with doc_hidden).
I had codex analyze your pruner to see if it depends on any behavior that's driven by the parser and it found two minor bugs.
A constructor body can be removed. Python normalizes the valid method name 𝒊nit to init. Ruff’s parser performs that normalization (line 442), but the linked pruner compares the raw source spelling. For class C: def 𝒊nit(self): ..., it would prune the constructor body, potentially removing self attributes from the AST Griffe examines. I confirmed with Python’s ast.parse that the method’s name is init. This is a parser-only normalization step, rather than lexer feedback.
A method body can be retained unnecessarily. In class C: def match(__init__): ..., the lexer emits Match for the method name; the parser accepts it as an identifier (line 518). The pruner only recognizes Name as a definition name, so it mistakes the parameter __init__ for the method name and keeps the body. That loses the intended speedup, but does not itself remove AST information. case has the same issue.
Activity
MichaReiser commentedon Sep 8, 2026
Thanks for the kind words and the nice words.
How do you detect a function body? Do you match based on seeing the first indent after a
defkeyword?In general, our lexer is not intended to be consumed directly. Unlike a lexer described in a classical compiler book, our lexer depends on a feedback loop with the parser to distinguish whether a contextual keywords is a keyword or a name in the current context (relevant for handling
matchandcase). I don't think this matters to you but we may use this mechanism for other language features in the future if necessary. Because of that, I mainly consider our lexer as internal. The only reasonlexis public is because it is required for benchmarking 😅Having said all this. I don't mind it terribly to make these methods public. Although I'm not sure why you'd need
current_flagsand I also can't guarantee that these methods will remain public or remain existing in the future.If you want to build on slightly more stable API, I'd suggest you to parse the AST, and take the range from the body's first and last statement. Unfortunately, this is likely to be a good deal slower than just lexing because Ruff has to allocate an AST. But I'm not sure if the difference is notable for your use case (it's still pretty fast) and it's likely also more resilient than guessing function bodies from the token stream.
The other alternative is that you simply copy the entire lexer module. It isn't that much code.
pawamoy commentedon Sep 8, 2026
Thanks!
The pruner uses Ruff’s lexer tokens:
Deftoken starts a function header.:only after the parameter list has closed, accounting for multiline signatures, nested delimiters, and lambda colons in return annotations.::Indentstarts an indented body.def f(): return 1.Dedentreturning below that body’s recorded indentation depth. An inline body ends at the logical Newline.If there's a multiline string (triple quoted string) in the middle of the function body, that still works because the string is parsed as a single
Stringtoken.Oh, right, that's exactly what I was doing before that, but it felt wasteful to lex+parse in Rust, then tokenize+parse again in Python through
compile(). It felt wasteful but it was already a performance improvement. I simply wanted to try and push it even further to maximize the performance gains (to compensate the added but well hidden complexity).For reference, the code is here: https://github.com/pawamoy/prune-source/. I used LLM assistance 🙂
pawamoy commentedon Sep 8, 2026
Oh and the pruner uses the flags only to distinguish between
"real docstring"andb"not a docstring"(Python doesn't consider byte strings as docstrings). Arguably this is an edge-case and we probably do not need it, but everything can be found in the wild so better be safe.pawamoy commentedon Sep 8, 2026
That'd be perfectly fine to me, I don't mind if API stability isn't guaranteed. It will already be super helpful because that means I don't have to vendor the code (keeping it up to date, while patching the two symbols everytime I update, etc.). But again, no worries if you don't think it's worth it, it's totally manageable on my end.
MichaReiser commentedon Sep 9, 2026
I see. I'm okay making these methods pub (but maybe with
doc_hidden).I had codex analyze your pruner to see if it depends on any behavior that's driven by the parser and it found two minor bugs.
A constructor body can be removed. Python normalizes the valid method name 𝒊nit to init. Ruff’s parser performs that normalization (line 442), but the linked pruner compares the raw source spelling. For class C: def 𝒊nit(self): ..., it would prune the constructor body, potentially removing self attributes from the AST Griffe examines. I confirmed with Python’s ast.parse that the method’s name is init. This is a parser-only normalization step, rather than lexer feedback.
A method body can be retained unnecessarily. In class
C: def match(__init__): ..., the lexer emitsMatchfor the method name; the parser accepts it as anidentifier(line 518). The pruner only recognizesNameas a definition name, so it mistakes the parameter__init__for the method name and keeps the body. That loses the intended speedup, but does not itself remove AST information. case has the same issue.pawamoy commentedon Sep 9, 2026
Thanks a lot! I was able to fix both issues 🙂