Skip to content

Fails to parse lambda in PEP 695 TypeVar bound #4599

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
15r10nk opened this issue Mar 2, 2025 · 2 comments · Fixed by #4602
Closed

Fails to parse lambda in PEP 695 TypeVar bound #4599

15r10nk opened this issue Mar 2, 2025 · 2 comments · Fixed by #4602
Labels
C: parser How we parse code. Or fail to parse it. T: bug Something isn't working

Comments

@15r10nk
Copy link

15r10nk commented Mar 2, 2025

Describe the bug

The following code can not be parsed/formatted by black:

class name_5[name_4: lambda: something]:
     pass
❯ black -t py312 bug.py
error: cannot format bug.py: Cannot parse for target version Python 3.12: 1:21: class name_5[name_4: lambda: something]:

Oh no! 💥 💔 💥
1 file failed to reformat.

but it can be parsed by cpython.

python3.12 scripts/min_code.py

Environment

  • Black's version: current main (00c0d6d)
  • OS and Python version: Linux/Python 3.12

Additional context

The bug was found by pysource-codegen (see #3908)

@15r10nk 15r10nk added the T: bug Something isn't working label Mar 2, 2025
@15r10nk 15r10nk changed the title parsing problem for annotated parsing problem for lambda inside typed class Mar 2, 2025
@JelleZijlstra JelleZijlstra added the C: parser How we parse code. Or fail to parse it. label Mar 3, 2025
@JelleZijlstra JelleZijlstra changed the title parsing problem for lambda inside typed class Fails to parse lambda in PEP 695 TypeVar bound Mar 3, 2025
@MeGaGiGaGon
Copy link
Collaborator

I did some digging, and this is a parser issue, it tokenizes the same as with the builtin tokenizer module. The error happens while parsing the lambda token, but I couldn’t go further than that with my usual technique since it’s just an error with the generated abstract machine having no valid transition states. I looked at the grammar.txt file, but at least the part about typeparams looks to match what’s in the python docs, so no clue.

@JelleZijlstra
Copy link
Collaborator

This turned out to be a simple fix, I had used the wrong expression kind in the grammar.

It also incorrectly rejects these in TypeVar defaults (new in 3.13), and in addition to lambdas it rejects if ... else, and, or, not, and comparisons (== etc.). Fortunately none of these make semantic sense here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
C: parser How we parse code. Or fail to parse it. T: bug Something isn't working
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants