Skip to content
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

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

Open
connernilsen opened this issue Jul 8, 2024 · 0 comments
Labels
C: crash Black is crashing T: bug Something isn't working

Comments

@connernilsen
Copy link

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

@connernilsen connernilsen added the T: bug Something isn't working label Jul 8, 2024
@JelleZijlstra JelleZijlstra added the C: crash Black is crashing label Jul 8, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
C: crash Black is crashing T: bug Something isn't working
Projects
None yet
Development

No branches or pull requests

2 participants