Skip to content

Black fails with ASTSafetyError on comment line in return type annotation #4399

@connernilsen

Description

@connernilsen

Hello, I recently hit a bug while working on adding type error suppressions to a codebase I'm working on.

Describe the bug

Black appears to add a Tuple to the AST when a comment is present in a multi-line return type annotation. This results in an ASTSafetyError and fails to lint the file.

To Reproduce

Run the following example file in the online editor

import typing as t

from my_library import Abstract
from my_other_library import api

_T = t.TypeVar("_T")

class MyClass(Generic[_T]):
    ...

def create_my_nested_class() -> (
    # some linter directive that need to be here
    MyClass
):
    class MyNestedClass(MyClass):
        pass
    return MyNestedClass

The resulting error is:

INTERNAL ERROR: Black produced code that is not equivalent to the source.  Please report a bug on https://github.com/psf/black/issues.  This diff might be helpful:

--- src
+++ dst
@@ -155,17 +155,23 @@
         )  # /Return
         decorator_list=
         name=
         'create_my_nested_class',  # str
         returns=
-        Name(
+        Tuple(
             ctx=
             Load(
             )  # /Load
-            id=
-            'MyClass',  # str
-        )  # /Name
+            elts=
+            Name(
+                ctx=
+                Load(
+                )  # /Load
+                id=
+                'MyClass',  # str
+            )  # /Name
+        )  # /Tuple
         type_comment=
         None,  # NoneType
     )  # /FunctionDef
     type_ignores=
 )  # /Module
\ No newline at end of file

Compiling with Python shows no issues

$ python3.10 -m py_compile example.py
$ echo $?
0

Expected behavior

No ASTSafetyError thrown, and file is successfully formatted with no functional changes.

Environment

Locally:

  • black.linux_x86_64, 24.4.2 (compiled: yes)
  • Python (CPython) 3.10.9
  • OS is Centos

Also reproduces on online editor above

Metadata

Metadata

Assignees

No one assigned

    Labels

    C: crashBlack is crashingT: bugSomething isn't working

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions