From 01b8d3d4095ebdb91d0d39012a517931625c63cb Mon Sep 17 00:00:00 2001 From: "Yilei \"Dolee\" Yang" Date: Thu, 15 Jun 2023 17:08:26 -0700 Subject: [PATCH] Do not add trailing commas to return type annotations using PEP 604 unions (#3735) Fix #3638: Do not add trailing commas to return type annotations using PEP 604 unions. --- CHANGES.md | 3 +++ src/black/linegen.py | 7 +++++++ tests/data/simple_cases/pep_604.py | 25 +++++++++++++++++++++++++ 3 files changed, 35 insertions(+) create mode 100644 tests/data/simple_cases/pep_604.py diff --git a/CHANGES.md b/CHANGES.md index 658faad..fd4d911 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -10,6 +10,9 @@ +- Fix a bug where an illegal trailing comma was added to return type annotations using + PEP 604 unions (#3735) + ### Preview style diff --git a/src/black/linegen.py b/src/black/linegen.py index 0091cbb..ad21307 100644 --- a/src/black/linegen.py +++ b/src/black/linegen.py @@ -918,6 +918,13 @@ def bracket_split_build_line( ) if isinstance(node, Node) and isinstance(node.prev_sibling, Leaf) ) + # Except the false negatives above for PEP 604 unions where we + # can't add the comma. + and not ( + leaves[0].parent + and leaves[0].parent.next_sibling + and leaves[0].parent.next_sibling.type == token.VBAR + ) ) if original.is_import or no_commas: diff --git a/tests/data/simple_cases/pep_604.py b/tests/data/simple_cases/pep_604.py new file mode 100644 index 0000000..b68d59d --- /dev/null +++ b/tests/data/simple_cases/pep_604.py @@ -0,0 +1,25 @@ +def some_very_long_name_function() -> my_module.Asdf | my_module.AnotherType | my_module.YetAnotherType | None: + pass + + +def some_very_long_name_function() -> my_module.Asdf | my_module.AnotherType | my_module.YetAnotherType | my_module.EvenMoreType | None: + pass + + +# output + + +def some_very_long_name_function() -> ( + my_module.Asdf | my_module.AnotherType | my_module.YetAnotherType | None +): + pass + + +def some_very_long_name_function() -> ( + my_module.Asdf + | my_module.AnotherType + | my_module.YetAnotherType + | my_module.EvenMoreType + | None +): + pass -- 2.39.5