Skip to content

fmt: off/on on different indentation levels leads to INTERNAL ERROR: Black produced invalid code on pass 1 #2140

Description

@mkhl

Placing several fmt: off/fmt: on comments, each around long with ... as ...: lines, leads to black raising an internal error

To Reproduce Steps to reproduce the behavior:

  1. Take this file foo.py
    name = "foo.py"
    
    
    def foo():
        # fmt: off
        with open(name) as f1, open(name) as f2, open(name) as f3, open(name) as f4, open(name) as f5:
            # fmt: on
            print(f1, f2, f3, f4, f5)
    
    
    def bar():
        # fmt: off
        with open(name) as f1, open(name) as f2, open(name) as f3, open(name) as f4, open(name) as f5:
            # fmt: on
            print(f1, f2, f3, f4, f5)
    
  2. Run Black on it with these arguments: black foo.py
  3. See error: error: cannot format foo.py: INTERNAL ERROR: Black produced invalid code on pass 1: invalid syntax (<unknown>, line 12). Please report a bug on https://github.com/psf/black/issues. This invalid output might be helpful: /tmp/blk_3i4qdouv.log

Expected behavior Black formats the source file, leaving the line marked to not be formatted alone.

Environment (please complete the following information):

  • Version: black, version 21.4b0
  • OS and Python version: Linux, Python 3.9.4

Does this bug also happen on master? Yes it does

Additional context Add any other context about the problem here.

The helpful diff:

Details
  File "/home/mkhl/.cache/pypoetry/virtualenvs/api-FV8o_s3F-py3.9/lib/python3.9/site-packages/black/__init__.py", line 6508, in assert_equivalent
    dst_ast = parse_ast(dst)
  File "/home/mkhl/.cache/pypoetry/virtualenvs/api-FV8o_s3F-py3.9/lib/python3.9/site-packages/black/__init__.py", line 6409, in parse_ast
    return ast27.parse(src)
  File "/home/mkhl/.cache/pypoetry/virtualenvs/api-FV8o_s3F-py3.9/lib64/python3.9/site-packages/typed_ast/ast27.py", line 50, in parse
    return _ast27.parse(source, filename, mode)
name = "foo.py"

def foo():
# fmt: off
with open(name) as f1, open(name) as f2, open(name) as f3, open(name) as f4, open(name) as f5:
# fmt: on
print(f1, f2, f3, f4, f5)

def bar():
    # fmt: off
with open(name) as f1, open(name) as f2, open(name) as f3, open(name) as f4, open(name) as f5:
    # fmt: on
    print(f1, f2, f3, f4, f5)

Metadata

Metadata

Assignees

No one assigned

    Labels

    F: fmtofffmt: off implementationT: bugSomething isn't working

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions