Skip to content

Parser fails due to empty body ... on same line as definition. Discrepancy in whole file and --line-ranges parsing #4669

Open
@Daraan

Description

@Daraan

Describe the bug

Originally I realized that in VSCode the black formatter does not format my code anymore, i.e. the --line-ranges is broken and raises a parser error.

Observation: Difference between black file.py and black --line-range #-# file.py

If there is a def foo(self): ... with ... on the same line black fails to format anything after when used with --line-range.

To Reproduce

For example, take this code:

class Foo:
    
    @overload
    def foo(self, *, a: int) -> None: ...
    
    def fox(self):
        print('This line is', 'way',  'way',  'way',  'way', 'too long to fit in a single line, so it is split into multiple lines for better readability.')

And run it with these arguments:

Fails:

$ black -c --line-ranges 6-7 "class Foo:
    
    @overload
    def foo(self, *, a: int) -> None: ...
    
    def fox(self):
        print('This line is', 'way',  'way',  'way',  'way', 'too long to fit in a single line, so it is split into multiple lines for better readability.')
"
error: cannot format <string>: Cannot parse for target version Python 3.11: 3:17:     @overload    def foo(self, *, a: int) -> None: ..

Formatting only the ... line changes nothing

$ black -c --line-ranges 1-5 "class Foo:
    
    @overload
    def foo(self, *, a: int) -> None: ...
    
    def fox(self):
        print('This line is', 'way',  'way',  'way',  'way', 'too long to fit in a single line, so it is split into multiple lines for better readability.')
"

# Trimmed output
    @overload
    def foo(self, *, a: int) -> None: ...

Works:

  • Either formatting everything without --line-ranges works correctly and does change the long line; also including the seemingly "broken" line seems to work fine.
  • First putting ... on the next line and then format it is fine:
$black -c "class Foo:
    
    @overload
    def foo(self, *, a: int) -> None:
        ...
    
    def fox(self):
        print('This line is', 'way',  'way',  'way',  'way', 'too long to fit in a single line, so it is split into multiple lines for better readability.')
" --line-ranges 7-9

In the end, if I format everything ... is again put on the same line and --line-ranges breaks for further editing.

Expected behavior

Parser should not be bothered if ... is on the same line or below anywhere, to have --line-ranges work everywhere independent of style used in above code.

Environment

Ubuntu 22.04

black, 25.1.0 (compiled: no)
Python (CPython) 3.10.16

2025-05-28 09:39:57.081 [info] SUPPORTED black>=22.3.0
FOUND black==25.1.0

Metadata

Metadata

Assignees

No one assigned

    Labels

    T: bugSomething isn't working

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions