repo
stringlengths
7
90
file_url
stringlengths
81
315
file_path
stringlengths
4
228
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 14:38:15
2026-01-05 02:33:18
truncated
bool
2 classes
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/f_docstring.py
tests/data/cases/f_docstring.py
def foo(e): f""" {'.'.join(e)}""" def bar(e): f"{'.'.join(e)}" def baz(e): F""" {'.'.join(e)}""" # output def foo(e): f""" {'.'.join(e)}""" def bar(e): f"{'.'.join(e)}" def baz(e): f""" {'.'.join(e)}"""
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/raw_docstring_no_string_normalization.py
tests/data/cases/raw_docstring_no_string_normalization.py
# flags: --skip-string-normalization def do_not_touch_this_prefix(): R"""There was a bug where docstring prefixes would be normalized even with -S.""" def do_not_touch_this_prefix2(): FR'There was a bug where docstring prefixes would be normalized even with -S.' def do_not_touch_this_prefix3(): u'''There was a bug where docstring prefixes would be normalized even with -S.'''
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/line_ranges_imports.py
tests/data/cases/line_ranges_imports.py
# flags: --line-ranges=8-8 # NOTE: If you need to modify this file, pay special attention to the --line-ranges= # flag above as it's formatting specifically these lines. # This test ensures no empty lines are added around import lines. # It caused an issue before https://github.com/psf/black/pull/3610 is merged. import os import re import sys
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/linelength6.py
tests/data/cases/linelength6.py
# flags: --line-length=6 # Regression test for #3427, which reproes only with line length <= 6 def f(): """ x """
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/string_prefixes.py
tests/data/cases/string_prefixes.py
#!/usr/bin/env python3 name = "Łukasz" (f"hello {name}", F"hello {name}") (b"", B"") (u"", U"") (r"", R"") (rf"", fr"", Rf"", fR"", rF"", Fr"", RF"", FR"") (rb"", br"", Rb"", bR"", rB"", Br"", RB"", BR"") def docstring_singleline(): R"""2020 was one hell of a year. The good news is that we were able to""" def docstring_multiline(): R""" clear out all of the issues opened in that time :p """ # output #!/usr/bin/env python3 name = "Łukasz" (f"hello {name}", f"hello {name}") (b"", b"") ("", "") (r"", R"") (rf"", rf"", Rf"", Rf"", rf"", rf"", Rf"", Rf"") (rb"", rb"", Rb"", Rb"", rb"", rb"", Rb"", Rb"") def docstring_singleline(): R"""2020 was one hell of a year. The good news is that we were able to""" def docstring_multiline(): R""" clear out all of the issues opened in that time :p """
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/trailing_comma.py
tests/data/cases/trailing_comma.py
e = { "a": fun(msg, "ts"), "longggggggggggggggid": ..., "longgggggggggggggggggggkey": ..., "created": ... # "longkey": ... } f = [ arg1, arg2, arg3, arg4 # comment ] g = ( arg1, arg2, arg3, arg4 # comment ) h = { arg1, arg2, arg3, arg4 # comment } # output e = { "a": fun(msg, "ts"), "longggggggggggggggid": ..., "longgggggggggggggggggggkey": ..., "created": ..., # "longkey": ... } f = [ arg1, arg2, arg3, arg4, # comment ] g = ( arg1, arg2, arg3, arg4, # comment ) h = { arg1, arg2, arg3, arg4, # comment }
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/annotations.py
tests/data/cases/annotations.py
# regression test for #1765 class Foo: def foo(self): if True: content_ids: Mapping[ str, Optional[ContentId] ] = self.publisher_content_store.store_config_contents(files) # output # regression test for #1765 class Foo: def foo(self): if True: content_ids: Mapping[str, Optional[ContentId]] = ( self.publisher_content_store.store_config_contents(files) )
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/function2.py
tests/data/cases/function2.py
def f( a, **kwargs, ) -> A: with cache_dir(): if something: result = ( CliRunner().invoke(black.main, [str(src1), str(src2), "--diff", "--check"]) ) limited.append(-limited.pop()) # negate top return A( very_long_argument_name1=very_long_value_for_the_argument, very_long_argument_name2=-very.long.value.for_the_argument, **kwargs, ) def g(): "Docstring." def inner(): pass print("Inner defs should breathe a little.") def h(): def inner(): pass print("Inner defs should breathe a little.") if os.name == "posix": import termios def i_should_be_followed_by_only_one_newline(): pass elif os.name == "nt": try: import msvcrt def i_should_be_followed_by_only_one_newline(): pass except ImportError: def i_should_be_followed_by_only_one_newline(): pass elif False: class IHopeYouAreHavingALovelyDay: def __call__(self): print("i_should_be_followed_by_only_one_newline") else: def foo(): pass with hmm_but_this_should_get_two_preceding_newlines(): pass # output def f( a, **kwargs, ) -> A: with cache_dir(): if something: result = CliRunner().invoke( black.main, [str(src1), str(src2), "--diff", "--check"] ) limited.append(-limited.pop()) # negate top return A( very_long_argument_name1=very_long_value_for_the_argument, very_long_argument_name2=-very.long.value.for_the_argument, **kwargs, ) def g(): "Docstring." def inner(): pass print("Inner defs should breathe a little.") def h(): def inner(): pass print("Inner defs should breathe a little.") if os.name == "posix": import termios def i_should_be_followed_by_only_one_newline(): pass elif os.name == "nt": try: import msvcrt def i_should_be_followed_by_only_one_newline(): pass except ImportError: def i_should_be_followed_by_only_one_newline(): pass elif False: class IHopeYouAreHavingALovelyDay: def __call__(self): print("i_should_be_followed_by_only_one_newline") else: def foo(): pass with hmm_but_this_should_get_two_preceding_newlines(): pass
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/pep_750.py
tests/data/cases/pep_750.py
# flags: --minimum-version=3.14 x = t"foo" x = t'foo {{ {2 + 2}bar {{ baz' x = t"foo {f'abc'} bar" x = t"""foo {{ a foo {2 + 2}bar {{ baz x = f"foo {{ { 2 + 2 # comment }bar" {{ baz }} buzz {print("abc" + "def" )} abc""" t'{(abc:=10)}' t'''This is a really long string, but just make sure that you reflow tstrings { 2+2:d }''' t'This is a really long string, but just make sure that you reflow tstrings correctly {2+2:d}' t"{ 2 + 2 = }" t'{ X !r }' tr'\{{\}}' t''' WITH {f''' {1}_cte AS ()'''} ''' # output x = t"foo" x = t"foo {{ {2 + 2}bar {{ baz" x = t"foo {f'abc'} bar" x = t"""foo {{ a foo {2 + 2}bar {{ baz x = f"foo {{ { 2 + 2 # comment }bar" {{ baz }} buzz {print("abc" + "def" )} abc""" t"{(abc:=10)}" t"""This is a really long string, but just make sure that you reflow tstrings { 2+2:d }""" t"This is a really long string, but just make sure that you reflow tstrings correctly {2+2:d}" t"{ 2 + 2 = }" t"{ X !r }" rt"\{{\}}" t""" WITH {f''' {1}_cte AS ()'''} """
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/python37.py
tests/data/cases/python37.py
def f(): return (i * 2 async for i in arange(42)) def g(): return ( something_long * something_long async for something_long in async_generator(with_an_argument) ) async def func(): await ... if test: out_batched = [ i async for i in aitertools._async_map( self.async_inc, arange(8), batch_size=3 ) ] def awaited_generator_value(n): return (await awaitable for awaitable in awaitable_list) def make_arange(n): return (i * 2 for i in range(n) if await wrap(i)) # output def f(): return (i * 2 async for i in arange(42)) def g(): return ( something_long * something_long async for something_long in async_generator(with_an_argument) ) async def func(): await ... if test: out_batched = [ i async for i in aitertools._async_map( self.async_inc, arange(8), batch_size=3 ) ] def awaited_generator_value(n): return (await awaitable for awaitable in awaitable_list) def make_arange(n): return (i * 2 for i in range(n) if await wrap(i))
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/fmtskip4.py
tests/data/cases/fmtskip4.py
a = 2 # fmt: skip l = [1, 2, 3,] # output a = 2 # fmt: skip l = [ 1, 2, 3, ]
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/fmtskip_multiple_in_clause.py
tests/data/cases/fmtskip_multiple_in_clause.py
# Multiple fmt: skip in multi-part if-clause class ClassWithALongName: Constant1 = 1 Constant2 = 2 Constant3 = 3 def test(): if ( "cond1" == "cond1" and "cond2" == "cond2" and 1 in ( ClassWithALongName.Constant1, ClassWithALongName.Constant2, ClassWithALongName.Constant3, # fmt: skip ) # fmt: skip ): return True return False # output # Multiple fmt: skip in multi-part if-clause class ClassWithALongName: Constant1 = 1 Constant2 = 2 Constant3 = 3 def test(): if ( "cond1" == "cond1" and "cond2" == "cond2" and 1 in ( ClassWithALongName.Constant1, ClassWithALongName.Constant2, ClassWithALongName.Constant3, # fmt: skip ) # fmt: skip ): return True return False
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/walrus_in_dict.py
tests/data/cases/walrus_in_dict.py
# flags: --preview # This is testing an issue that is specific to the preview style (wrap_long_dict_values_in_parens) { "is_update": (up := commit.hash in update_hashes) } # output # This is testing an issue that is specific to the preview style (wrap_long_dict_values_in_parens) {"is_update": (up := commit.hash in update_hashes)}
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/remove_lone_list_item_parens.py
tests/data/cases/remove_lone_list_item_parens.py
items = [(123)] items = [(True)] items = [(((((True)))))] items = [(((((True,)))))] items = [((((()))))] items = [(x for x in [1])] items = {(123)} items = {(True)} items = {(((((True)))))} # Requires `hug_parens_with_braces_and_square_brackets` unstable style to remove parentheses # around multiline values items = [ ( {"key1": "val1", "key2": "val2", "key3": "val3"} if some_var == "long strings" else {"key": "val"} ) ] items = [ ( {"key1": "val1", "key2": "val2"} if some_var == "" else {"key": "val"} ) ] # Comments should not cause crashes items = [ ( # comment {"key1": "val1", "key2": "val2", "key3": "val3"} if some_var == "long strings" else {"key": "val"} ) ] items = [ ( {"key1": "val1", "key2": "val2", "key3": "val3"} if some_var == "long strings" else {"key": "val"} ) # comment ] items = [ # comment ( {"key1": "val1", "key2": "val2", "key3": "val3"} if some_var == "long strings" else {"key": "val"} ) ] items = [ ( {"key1": "val1", "key2": "val2", "key3": "val3"} if some_var == "long strings" else {"key": "val"} ) ] # comment items = [ ( {"key1": "val1", "key2": "val2", "key3": "val3"} # comment if some_var == "long strings" else {"key": "val"} ) ] items = [ # comment ( # comment {"key1": "val1", "key2": "val2", "key3": "val3"} if some_var == "long strings" else {"key": "val"} ) ] items = [ ( {"key1": "val1", "key2": "val2", "key3": "val3"} if some_var == "long strings" else {"key": "val"} ) # comment ] # comment # output items = [123] items = [True] items = [True] items = [(True,)] items = [()] items = [(x for x in [1])] items = {123} items = {True} items = {True} # Requires `hug_parens_with_braces_and_square_brackets` unstable style to remove parentheses # around multiline values items = [ ( {"key1": "val1", "key2": "val2", "key3": "val3"} if some_var == "long strings" else {"key": "val"} ) ] items = [{"key1": "val1", "key2": "val2"} if some_var == "" else {"key": "val"}] # Comments should not cause crashes items = [ ( # comment {"key1": "val1", "key2": "val2", "key3": "val3"} if some_var == "long strings" else {"key": "val"} ) ] items = [ ( {"key1": "val1", "key2": "val2", "key3": "val3"} if some_var == "long strings" else {"key": "val"} ) # comment ] items = [ # comment ( {"key1": "val1", "key2": "val2", "key3": "val3"} if some_var == "long strings" else {"key": "val"} ) ] items = [ ( {"key1": "val1", "key2": "val2", "key3": "val3"} if some_var == "long strings" else {"key": "val"} ) ] # comment items = [ ( {"key1": "val1", "key2": "val2", "key3": "val3"} # comment if some_var == "long strings" else {"key": "val"} ) ] items = [ # comment ( # comment {"key1": "val1", "key2": "val2", "key3": "val3"} if some_var == "long strings" else {"key": "val"} ) ] items = [ ( {"key1": "val1", "key2": "val2", "key3": "val3"} if some_var == "long strings" else {"key": "val"} ) # comment ] # comment
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/cantfit.py
tests/data/cases/cantfit.py
# long variable name this_is_a_ridiculously_long_name_and_nobody_in_their_right_mind_would_use_one_like_it = 0 this_is_a_ridiculously_long_name_and_nobody_in_their_right_mind_would_use_one_like_it = 1 # with a comment this_is_a_ridiculously_long_name_and_nobody_in_their_right_mind_would_use_one_like_it = [ 1, 2, 3 ] this_is_a_ridiculously_long_name_and_nobody_in_their_right_mind_would_use_one_like_it = function() this_is_a_ridiculously_long_name_and_nobody_in_their_right_mind_would_use_one_like_it = function( arg1, arg2, arg3 ) this_is_a_ridiculously_long_name_and_nobody_in_their_right_mind_would_use_one_like_it = function( [1, 2, 3], arg1, [1, 2, 3], arg2, [1, 2, 3], arg3 ) # long function name normal_name = but_the_function_name_is_now_ridiculously_long_and_it_is_still_super_annoying() normal_name = but_the_function_name_is_now_ridiculously_long_and_it_is_still_super_annoying( arg1, arg2, arg3 ) normal_name = but_the_function_name_is_now_ridiculously_long_and_it_is_still_super_annoying( [1, 2, 3], arg1, [1, 2, 3], arg2, [1, 2, 3], arg3 ) string_variable_name = ( "a string that is waaaaaaaayyyyyyyy too long, even in parens, there's nothing you can do" # noqa ) for key in """ hostname port username """.split(): if key in self.connect_kwargs: raise ValueError(err.format(key)) concatenated_strings = "some strings that are " "concatenated implicitly, so if you put them on separate " "lines it will fit" del concatenated_strings, string_variable_name, normal_function_name, normal_name, need_more_to_make_the_line_long_enough del ([], name_1, name_2), [(), [], name_4, name_3], name_1[[name_2 for name_1 in name_0]] del (), # output # long variable name this_is_a_ridiculously_long_name_and_nobody_in_their_right_mind_would_use_one_like_it = ( 0 ) this_is_a_ridiculously_long_name_and_nobody_in_their_right_mind_would_use_one_like_it = ( 1 # with a comment ) this_is_a_ridiculously_long_name_and_nobody_in_their_right_mind_would_use_one_like_it = [ 1, 2, 3, ] this_is_a_ridiculously_long_name_and_nobody_in_their_right_mind_would_use_one_like_it = ( function() ) this_is_a_ridiculously_long_name_and_nobody_in_their_right_mind_would_use_one_like_it = function( arg1, arg2, arg3 ) this_is_a_ridiculously_long_name_and_nobody_in_their_right_mind_would_use_one_like_it = function( [1, 2, 3], arg1, [1, 2, 3], arg2, [1, 2, 3], arg3 ) # long function name normal_name = ( but_the_function_name_is_now_ridiculously_long_and_it_is_still_super_annoying() ) normal_name = ( but_the_function_name_is_now_ridiculously_long_and_it_is_still_super_annoying( arg1, arg2, arg3 ) ) normal_name = ( but_the_function_name_is_now_ridiculously_long_and_it_is_still_super_annoying( [1, 2, 3], arg1, [1, 2, 3], arg2, [1, 2, 3], arg3 ) ) string_variable_name = "a string that is waaaaaaaayyyyyyyy too long, even in parens, there's nothing you can do" # noqa for key in """ hostname port username """.split(): if key in self.connect_kwargs: raise ValueError(err.format(key)) concatenated_strings = ( "some strings that are " "concatenated implicitly, so if you put them on separate " "lines it will fit" ) del ( concatenated_strings, string_variable_name, normal_function_name, normal_name, need_more_to_make_the_line_long_enough, ) del ( ([], name_1, name_2), [(), [], name_4, name_3], name_1[[name_2 for name_1 in name_0]], ) del ((),)
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/target_version_flag.py
tests/data/cases/target_version_flag.py
# flags: --minimum-version=3.12 --target-version=py312 # this is invalid in versions below py312 class ClassA[T: str]: def method1(self) -> T: ... # output # this is invalid in versions below py312 class ClassA[T: str]: def method1(self) -> T: ...
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/form_feeds.py
tests/data/cases/form_feeds.py
# Warning! This file contains form feeds (ASCII 0x0C, often represented by \f or ^L). # These may be invisible in your editor: ensure you can see them before making changes here. # There's one at the start that'll get stripped # Comment and statement processing is different enough that we'll test variations of both # contexts here # # # # # # # # # # \ # pass pass pass pass pass pass pass pass pass pass pass # form feed after a dedent def foo(): pass pass # form feeds are prohibited inside blocks, or on a line with nonwhitespace def bar( a = 1 ,b : bool = False ) : pass class Baz: def __init__(self): pass def something(self): pass # pass pass # a = 1 # pass a = 1 a = [ ] # as internal whitespace of a comment is allowed but why "form feed literal in a string is okay " # form feeds at the very end get removed. # output # Warning! This file contains form feeds (ASCII 0x0C, often represented by \f or ^L). # These may be invisible in your editor: ensure you can see them before making changes here. # There's one at the start that'll get stripped # Comment and statement processing is different enough that we'll test variations of both # contexts here # # # # # # # # # # # pass pass pass pass pass pass pass pass pass pass pass # form feed after a dedent def foo(): pass pass # form feeds are prohibited inside blocks, or on a line with nonwhitespace def bar(a=1, b: bool = False): pass class Baz: def __init__(self): pass def something(self): pass # pass pass # a = 1 # pass a = 1 a = [] # as internal whitespace of a comment is allowed but why "form feed literal in a string is okay " # form feeds at the very end get removed.
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/fmtskip_multiple_strings.py
tests/data/cases/fmtskip_multiple_strings.py
# Multiple fmt: skip on string literals a = ( "this should " # fmt: skip "be fine" ) b = ( "this is " # fmt: skip "not working" # fmt: skip ) c = ( "and neither " # fmt: skip "is this " # fmt: skip "working" ) d = ( "nor " "is this " # fmt: skip "working" # fmt: skip ) e = ( "and this " # fmt: skip "is definitely " "not working" # fmt: skip ) # Dictionary entries with fmt: skip (covers issue with long lines) hotkeys = { "editor:swap-line-down": [{"key": "ArrowDown", "modifiers": ["Alt", "Mod"]}], # fmt: skip "editor:swap-line-up": [{"key": "ArrowUp", "modifiers": ["Alt", "Mod"]}], # fmt: skip "editor:toggle-source": [{"key": "S", "modifiers": ["Alt", "Mod"]}], # fmt: skip } # output # Multiple fmt: skip on string literals a = ( "this should " # fmt: skip "be fine" ) b = ( "this is " # fmt: skip "not working" # fmt: skip ) c = ( "and neither " # fmt: skip "is this " # fmt: skip "working" ) d = ( "nor " "is this " # fmt: skip "working" # fmt: skip ) e = ( "and this " # fmt: skip "is definitely " "not working" # fmt: skip ) # Dictionary entries with fmt: skip (covers issue with long lines) hotkeys = { "editor:swap-line-down": [{"key": "ArrowDown", "modifiers": ["Alt", "Mod"]}], # fmt: skip "editor:swap-line-up": [{"key": "ArrowUp", "modifiers": ["Alt", "Mod"]}], # fmt: skip "editor:toggle-source": [{"key": "S", "modifiers": ["Alt", "Mod"]}], # fmt: skip }
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/generics_wrapping.py
tests/data/cases/generics_wrapping.py
# flags: --minimum-version=3.12 def plain[T, B](a: T, b: T) -> T: return a def arg_magic[T, B](a: T, b: T,) -> T: return a def type_param_magic[T, B,](a: T, b: T) -> T: return a def both_magic[T, B,](a: T, b: T,) -> T: return a def plain_multiline[ T, B ]( a: T, b: T ) -> T: return a def arg_magic_multiline[ T, B ]( a: T, b: T, ) -> T: return a def type_param_magic_multiline[ T, B, ]( a: T, b: T ) -> T: return a def both_magic_multiline[ T, B, ]( a: T, b: T, ) -> T: return a def plain_mixed1[ T, B ](a: T, b: T) -> T: return a def plain_mixed2[T, B]( a: T, b: T ) -> T: return a def arg_magic_mixed1[ T, B ](a: T, b: T,) -> T: return a def arg_magic_mixed2[T, B]( a: T, b: T, ) -> T: return a def type_param_magic_mixed1[ T, B, ](a: T, b: T) -> T: return a def type_param_magic_mixed2[T, B,]( a: T, b: T ) -> T: return a def both_magic_mixed1[ T, B, ](a: T, b: T,) -> T: return a def both_magic_mixed2[T, B,]( a: T, b: T, ) -> T: return a def something_something_function[ T: Model ](param: list[int], other_param: type[T], *, some_other_param: bool = True) -> QuerySet[ T ]: pass def func[A_LOT_OF_GENERIC_TYPES: AreBeingDefinedHere, LIKE_THIS, AND_THIS, ANOTHER_ONE, AND_YET_ANOTHER_ONE: ThisOneHasTyping](a: T, b: T, c: T, d: T, e: T, f: T, g: T, h: T, i: T, j: T, k: T, l: T, m: T, n: T, o: T, p: T) -> T: return a def with_random_comments[ Z # bye ](): return a def func[ T, # comment U # comment , Z: # comment int ](): pass def func[ T, # comment but it's long so it doesn't just move to the end of the line U # comment comment comm comm ent ent , Z: # comment ent ent comm comm comment int ](): pass # output def plain[T, B](a: T, b: T) -> T: return a def arg_magic[T, B]( a: T, b: T, ) -> T: return a def type_param_magic[ T, B, ]( a: T, b: T ) -> T: return a def both_magic[ T, B, ]( a: T, b: T, ) -> T: return a def plain_multiline[T, B](a: T, b: T) -> T: return a def arg_magic_multiline[T, B]( a: T, b: T, ) -> T: return a def type_param_magic_multiline[ T, B, ]( a: T, b: T ) -> T: return a def both_magic_multiline[ T, B, ]( a: T, b: T, ) -> T: return a def plain_mixed1[T, B](a: T, b: T) -> T: return a def plain_mixed2[T, B](a: T, b: T) -> T: return a def arg_magic_mixed1[T, B]( a: T, b: T, ) -> T: return a def arg_magic_mixed2[T, B]( a: T, b: T, ) -> T: return a def type_param_magic_mixed1[ T, B, ]( a: T, b: T ) -> T: return a def type_param_magic_mixed2[ T, B, ]( a: T, b: T ) -> T: return a def both_magic_mixed1[ T, B, ]( a: T, b: T, ) -> T: return a def both_magic_mixed2[ T, B, ]( a: T, b: T, ) -> T: return a def something_something_function[T: Model]( param: list[int], other_param: type[T], *, some_other_param: bool = True ) -> QuerySet[T]: pass def func[ A_LOT_OF_GENERIC_TYPES: AreBeingDefinedHere, LIKE_THIS, AND_THIS, ANOTHER_ONE, AND_YET_ANOTHER_ONE: ThisOneHasTyping, ]( a: T, b: T, c: T, d: T, e: T, f: T, g: T, h: T, i: T, j: T, k: T, l: T, m: T, n: T, o: T, p: T, ) -> T: return a def with_random_comments[ Z # bye ](): return a def func[T, U, Z: int](): # comment # comment # comment pass def func[ T, # comment but it's long so it doesn't just move to the end of the line U, # comment comment comm comm ent ent Z: int, # comment ent ent comm comm comment ](): pass
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/funcdef_return_type_trailing_comma.py
tests/data/cases/funcdef_return_type_trailing_comma.py
# flags: --minimum-version=3.10 # normal, short, function definition def foo(a, b) -> tuple[int, float]: ... # normal, short, function definition w/o return type def foo(a, b): ... # no splitting def foo(a: A, b: B) -> list[p, q]: pass # magic trailing comma in param list def foo(a, b,): ... # magic trailing comma in nested params in param list def foo(a, b: tuple[int, float,]): ... # magic trailing comma in return type, no params def a() -> tuple[ a, b, ]: ... # magic trailing comma in return type, params def foo(a: A, b: B) -> list[ p, q, ]: pass # magic trailing comma in param list and in return type def foo( a: a, b: b, ) -> list[ a, a, ]: pass # long function definition, param list is longer def aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa( bbbbbbbbbbbbbbbbbb, ) -> cccccccccccccccccccccccccccccc: ... # long function definition, return type is longer # this should maybe split on rhs? def aaaaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbb) -> list[ Ccccccccccccccccccccccccccccccccccccccccccccccccccc, Dddddd ]: ... # long return type, no param list def foo() -> list[ Loooooooooooooooooooooooooooooooooooong, Loooooooooooooooooooong, Looooooooooooong, ]: ... # long function name, no param list, no return value def thiiiiiiiiiiiiiiiiiis_iiiiiiiiiiiiiiiiiiiiiiiiiiiiiis_veeeeeeeeeeeeeeeeeeeeeeery_looooooong(): pass # long function name, no param list def thiiiiiiiiiiiiiiiiiis_iiiiiiiiiiiiiiiiiiiiiiiiiiiiiis_veeeeeeeeeeeeeeeeeeeeeeery_looooooong() -> ( list[int, float] ): ... # long function name, no return value def thiiiiiiiiiiiiiiiiiis_iiiiiiiiiiiiiiiiiiiiiiiiiiiiiis_veeeeeeeeeeeeeeeeeeeeeeery_looooooong( a, b ): ... # unskippable type hint (??) def foo(a) -> list[aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]: # type: ignore pass def foo(a) -> list[ aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ]: # abpedeifnore pass def foo(a, b: list[Bad],): ... # type: ignore # don't lose any comments (no magic) def foo( # 1 a, # 2 b) -> list[ # 3 a, # 4 b]: # 5 ... # 6 # don't lose any comments (param list magic) def foo( # 1 a, # 2 b,) -> list[ # 3 a, # 4 b]: # 5 ... # 6 # don't lose any comments (return type magic) def foo( # 1 a, # 2 b) -> list[ # 3 a, # 4 b,]: # 5 ... # 6 # don't lose any comments (both magic) def foo( # 1 a, # 2 b,) -> list[ # 3 a, # 4 b,]: # 5 ... # 6 # real life example def SimplePyFn( context: hl.GeneratorContext, buffer_input: Buffer[UInt8, 2], func_input: Buffer[Int32, 2], float_arg: Scalar[Float32], offset: int = 0, ) -> tuple[ Buffer[UInt8, 2], Buffer[UInt8, 2], ]: ... # output # normal, short, function definition def foo(a, b) -> tuple[int, float]: ... # normal, short, function definition w/o return type def foo(a, b): ... # no splitting def foo(a: A, b: B) -> list[p, q]: pass # magic trailing comma in param list def foo( a, b, ): ... # magic trailing comma in nested params in param list def foo( a, b: tuple[ int, float, ], ): ... # magic trailing comma in return type, no params def a() -> tuple[ a, b, ]: ... # magic trailing comma in return type, params def foo(a: A, b: B) -> list[ p, q, ]: pass # magic trailing comma in param list and in return type def foo( a: a, b: b, ) -> list[ a, a, ]: pass # long function definition, param list is longer def aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa( bbbbbbbbbbbbbbbbbb, ) -> cccccccccccccccccccccccccccccc: ... # long function definition, return type is longer # this should maybe split on rhs? def aaaaaaaaaaaaaaaaa( bbbbbbbbbbbbbbbbbb, ) -> list[Ccccccccccccccccccccccccccccccccccccccccccccccccccc, Dddddd]: ... # long return type, no param list def foo() -> list[ Loooooooooooooooooooooooooooooooooooong, Loooooooooooooooooooong, Looooooooooooong, ]: ... # long function name, no param list, no return value def thiiiiiiiiiiiiiiiiiis_iiiiiiiiiiiiiiiiiiiiiiiiiiiiiis_veeeeeeeeeeeeeeeeeeeeeeery_looooooong(): pass # long function name, no param list def thiiiiiiiiiiiiiiiiiis_iiiiiiiiiiiiiiiiiiiiiiiiiiiiiis_veeeeeeeeeeeeeeeeeeeeeeery_looooooong() -> ( list[int, float] ): ... # long function name, no return value def thiiiiiiiiiiiiiiiiiis_iiiiiiiiiiiiiiiiiiiiiiiiiiiiiis_veeeeeeeeeeeeeeeeeeeeeeery_looooooong( a, b ): ... # unskippable type hint (??) def foo(a) -> list[aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]: # type: ignore pass def foo( a, ) -> list[ aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ]: # abpedeifnore pass def foo( a, b: list[Bad], ): ... # type: ignore # don't lose any comments (no magic) def foo(a, b) -> list[a, b]: # 1 # 2 # 3 # 4 # 5 ... # 6 # don't lose any comments (param list magic) def foo( # 1 a, # 2 b, ) -> list[a, b]: # 3 # 4 # 5 ... # 6 # don't lose any comments (return type magic) def foo(a, b) -> list[ # 1 # 2 # 3 a, # 4 b, ]: # 5 ... # 6 # don't lose any comments (both magic) def foo( # 1 a, # 2 b, ) -> list[ # 3 a, # 4 b, ]: # 5 ... # 6 # real life example def SimplePyFn( context: hl.GeneratorContext, buffer_input: Buffer[UInt8, 2], func_input: Buffer[Int32, 2], float_arg: Scalar[Float32], offset: int = 0, ) -> tuple[ Buffer[UInt8, 2], Buffer[UInt8, 2], ]: ...
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/pep_654_style.py
tests/data/cases/pep_654_style.py
# flags: --minimum-version=3.11 try: raise OSError("blah") except * ExceptionGroup as e: pass try: async with trio.open_nursery() as nursery: # Make two concurrent calls to child() nursery.start_soon(child) nursery.start_soon(child) except *ValueError: pass try: try: raise ValueError(42) except: try: raise TypeError(int) except *(Exception): pass 1 / 0 except Exception as e: exc = e try: try: raise FalsyEG("eg", [TypeError(1), ValueError(2)]) except \ *TypeError as e: tes = e raise except * ValueError as e: ves = e pass except Exception as e: exc = e try: try: raise orig except *(TypeError, ValueError, *OTHER_EXCEPTIONS) as e: raise SyntaxError(3) from e except BaseException as e: exc = e try: try: raise orig except\ * OSError as e: raise TypeError(3) from e except ExceptionGroup as e: exc = e # output try: raise OSError("blah") except* ExceptionGroup as e: pass try: async with trio.open_nursery() as nursery: # Make two concurrent calls to child() nursery.start_soon(child) nursery.start_soon(child) except* ValueError: pass try: try: raise ValueError(42) except: try: raise TypeError(int) except* Exception: pass 1 / 0 except Exception as e: exc = e try: try: raise FalsyEG("eg", [TypeError(1), ValueError(2)]) except* TypeError as e: tes = e raise except* ValueError as e: ves = e pass except Exception as e: exc = e try: try: raise orig except* (TypeError, ValueError, *OTHER_EXCEPTIONS) as e: raise SyntaxError(3) from e except BaseException as e: exc = e try: try: raise orig except* OSError as e: raise TypeError(3) from e except ExceptionGroup as e: exc = e
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/docstring_no_extra_empty_line_before_eof.py
tests/data/cases/docstring_no_extra_empty_line_before_eof.py
# Make sure when the file ends with class's docstring, # It doesn't add extra blank lines. class ClassWithDocstring: """A docstring."""
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/context_managers_autodetect_311.py
tests/data/cases/context_managers_autodetect_311.py
# flags: --minimum-version=3.11 # This file uses except* clause in Python 3.11. try: some_call() except* Error as e: pass with \ make_context_manager1() as cm1, \ make_context_manager2() as cm2, \ make_context_manager3() as cm3, \ make_context_manager4() as cm4 \ : pass # output # This file uses except* clause in Python 3.11. try: some_call() except* Error as e: pass with ( make_context_manager1() as cm1, make_context_manager2() as cm2, make_context_manager3() as cm3, make_context_manager4() as cm4, ): pass
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/fmtonoff6.py
tests/data/cases/fmtonoff6.py
# Regression test for https://github.com/psf/black/issues/2478. def foo(): arr = ( (3833567325051000, 5, 1, 2, 4229.25, 6, 0), # fmt: off ) # Regression test for https://github.com/psf/black/issues/3458. dependencies = { a: b, # fmt: off }
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/pep_701.py
tests/data/cases/pep_701.py
# flags: --minimum-version=3.12 x = f"foo" x = f'foo' x = f"""foo""" x = f'''foo''' x = f"foo {{ bar {{ baz" x = f"foo {{ {2 + 2}bar {{ baz" x = f'foo {{ {2 + 2}bar {{ baz' x = f"""foo {{ {2 + 2}bar {{ baz""" x = f'''foo {{ {2 + 2}bar {{ baz''' # edge case: FSTRING_MIDDLE containing only whitespace should not be stripped x = f"{a} {b}" x = f"foo { 2 + 2 } bar baz" x = f"foo {{ {"a {2 + 2} b"}bar {{ baz" x = f"foo {{ {f'a {2 + 2} b'}bar {{ baz" x = f"foo {{ {f"a {2 + 2} b"}bar {{ baz" x = f"foo {{ {f'a {f"a {2 + 2} b"} b'}bar {{ baz" x = f"foo {{ {f"a {f"a {2 + 2} b"} b"}bar {{ baz" x = """foo {{ {2 + 2}bar baz""" x = f"""foo {{ {2 + 2}bar {{ baz""" x = f"""foo {{ { 2 + 2 }bar {{ baz""" x = f"""foo {{ { 2 + 2 }bar baz""" x = f"""foo {{ a foo {2 + 2}bar {{ baz x = f"foo {{ { 2 + 2 # comment }bar" {{ baz }} buzz {print("abc" + "def" )} abc""" # edge case: end triple quotes at index zero f"""foo {2+2} bar """ f' \' {f"'"} \' ' f" \" {f'"'} \" " x = f"a{2+2:=^72}b" x = f"a{2+2:x}b" rf'foo' rf'{foo}' f"{x:{y}d}" x = f"a{2+2:=^{x}}b" x = f"a{2+2:=^{foo(x+y**2):something else}}b" x = f"a{2+2:=^{foo(x+y**2):something else}one more}b" f'{(abc:=10)}' f"""This is a really long string, but just make sure that you reflow fstrings { 2+2:d }""" f"This is a really long string, but just make sure that you reflow fstrings correctly {2+2:d}" f"{2+2=}" f"{2+2 = }" f"{ 2 + 2 = }" f"""foo { datetime.datetime.now():%Y %m %d }""" f"{ X !r }" raise ValueError( "xxxxxxxxxxxIncorrect --line-ranges format, expect START-END, found" f" {lines_str!r}" ) f"`escape` only permitted in {{'html', 'latex', 'latex-math'}}, \ got {escape}" x = f'\N{GREEK CAPITAL LETTER DELTA} \N{SNOWMAN} {x}' fr'\{{\}}' f""" WITH {f''' {1}_cte AS ()'''} """ value: str = f'''foo ''' log( f"Received operation {server_operation.name} from " f"{self.writer._transport.get_extra_info('peername')}", # type: ignore[attr-defined] level=0, ) f"{1:{f'{2}'}}" f'{1:{f'{2}'}}' f'{1:{2}d}' f'{{\\"kind\\":\\"ConfigMap\\",\\"metadata\\":{{\\"annotations\\":{{}},\\"name\\":\\"cluster-info\\",\\"namespace\\":\\"amazon-cloudwatch\\"}}}}' f"""{''' '''}""" f"{'\''}" f"{f'\''}" f'{1}\{{' f'{2} foo \{{[\}}' f'\{3}' rf"\{"a"}" # output x = f"foo" x = f"foo" x = f"""foo""" x = f"""foo""" x = f"foo {{ bar {{ baz" x = f"foo {{ {2 + 2}bar {{ baz" x = f"foo {{ {2 + 2}bar {{ baz" x = f"""foo {{ {2 + 2}bar {{ baz""" x = f"""foo {{ {2 + 2}bar {{ baz""" # edge case: FSTRING_MIDDLE containing only whitespace should not be stripped x = f"{a} {b}" x = f"foo { 2 + 2 } bar baz" x = f"foo {{ {"a {2 + 2} b"}bar {{ baz" x = f"foo {{ {f'a {2 + 2} b'}bar {{ baz" x = f"foo {{ {f"a {2 + 2} b"}bar {{ baz" x = f"foo {{ {f'a {f"a {2 + 2} b"} b'}bar {{ baz" x = f"foo {{ {f"a {f"a {2 + 2} b"} b"}bar {{ baz" x = """foo {{ {2 + 2}bar baz""" x = f"""foo {{ {2 + 2}bar {{ baz""" x = f"""foo {{ { 2 + 2 }bar {{ baz""" x = f"""foo {{ { 2 + 2 }bar baz""" x = f"""foo {{ a foo {2 + 2}bar {{ baz x = f"foo {{ { 2 + 2 # comment }bar" {{ baz }} buzz {print("abc" + "def" )} abc""" # edge case: end triple quotes at index zero f"""foo {2+2} bar """ f' \' {f"'"} \' ' f" \" {f'"'} \" " x = f"a{2+2:=^72}b" x = f"a{2+2:x}b" rf"foo" rf"{foo}" f"{x:{y}d}" x = f"a{2+2:=^{x}}b" x = f"a{2+2:=^{foo(x+y**2):something else}}b" x = f"a{2+2:=^{foo(x+y**2):something else}one more}b" f"{(abc:=10)}" f"""This is a really long string, but just make sure that you reflow fstrings { 2+2:d }""" f"This is a really long string, but just make sure that you reflow fstrings correctly {2+2:d}" f"{2+2=}" f"{2+2 = }" f"{ 2 + 2 = }" f"""foo { datetime.datetime.now():%Y %m %d }""" f"{ X !r }" raise ValueError( "xxxxxxxxxxxIncorrect --line-ranges format, expect START-END, found" f" {lines_str!r}" ) f"`escape` only permitted in {{'html', 'latex', 'latex-math'}}, \ got {escape}" x = f"\N{GREEK CAPITAL LETTER DELTA} \N{SNOWMAN} {x}" rf"\{{\}}" f""" WITH {f''' {1}_cte AS ()'''} """ value: str = f"""foo """ log( f"Received operation {server_operation.name} from " f"{self.writer._transport.get_extra_info('peername')}", # type: ignore[attr-defined] level=0, ) f"{1:{f'{2}'}}" f"{1:{f'{2}'}}" f"{1:{2}d}" f'{{\\"kind\\":\\"ConfigMap\\",\\"metadata\\":{{\\"annotations\\":{{}},\\"name\\":\\"cluster-info\\",\\"namespace\\":\\"amazon-cloudwatch\\"}}}}' f"""{''' '''}""" f"{'\''}" f"{f'\''}" f"{1}\{{" f"{2} foo \{{[\}}" f"\{3}" rf"\{"a"}"
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/multiline_consecutive_open_parentheses_ignore.py
tests/data/cases/multiline_consecutive_open_parentheses_ignore.py
# This is a regression test. Issue #3737 a = ( # type: ignore int( # type: ignore int( # type: ignore int( # type: ignore 6 ) ) ) ) b = ( int( 6 ) ) print( "111") # type: ignore print( "111" ) # type: ignore print( "111" ) # type: ignore # output # This is a regression test. Issue #3737 a = ( # type: ignore int( # type: ignore int( # type: ignore int(6) # type: ignore ) ) ) b = int(6) print("111") # type: ignore print("111") # type: ignore print("111") # type: ignore
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/line_ranges_outside_source.py
tests/data/cases/line_ranges_outside_source.py
# flags: --line-ranges=5000-6000 # NOTE: If you need to modify this file, pay special attention to the --line-ranges= # flag above as it's formatting specifically these lines, in this case none. def foo1(parameter_1, parameter_2, parameter_3, parameter_4, parameter_5, parameter_6, parameter_7): pass def foo2(parameter_1, parameter_2, parameter_3, parameter_4, parameter_5, parameter_6, parameter_7): pass def foo3(parameter_1, parameter_2, parameter_3, parameter_4, parameter_5, parameter_6, parameter_7): pass def foo4(parameter_1, parameter_2, parameter_3, parameter_4, parameter_5, parameter_6, parameter_7): pass
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/composition_no_trailing_comma.py
tests/data/cases/composition_no_trailing_comma.py
class C: def test(self) -> None: with patch("black.out", print): self.assertEqual( unstyle(str(report)), "1 file reformatted, 1 file failed to reformat." ) self.assertEqual( unstyle(str(report)), "1 file reformatted, 1 file left unchanged, 1 file failed to reformat.", ) self.assertEqual( unstyle(str(report)), "2 files reformatted, 1 file left unchanged, 1 file failed to" " reformat.", ) self.assertEqual( unstyle(str(report)), "2 files reformatted, 2 files left unchanged, 2 files failed to" " reformat.", ) for i in (a,): if ( # Rule 1 i % 2 == 0 # Rule 2 and i % 3 == 0 ): while ( # Just a comment call() # Another ): print(i) xxxxxxxxxxxxxxxx = Yyyy2YyyyyYyyyyy( push_manager=context.request.resource_manager, max_items_to_push=num_items, batch_size=Yyyy2YyyyYyyyyYyyy.FULL_SIZE ).push( # Only send the first n items. items=items[:num_items] ) return ( 'Utterly failed doctest test for %s\n File "%s", line %s, in %s\n\n%s' % (test.name, test.filename, lineno, lname, err) ) def omitting_trailers(self) -> None: get_collection( hey_this_is_a_very_long_call, it_has_funny_attributes, really=True )[OneLevelIndex] get_collection( hey_this_is_a_very_long_call, it_has_funny_attributes, really=True )[OneLevelIndex][TwoLevelIndex][ThreeLevelIndex][FourLevelIndex] d[0][1][2][3][4][5][6][7][8][9][10][11][12][13][14][15][16][17][18][19][20][21][ 22 ] assignment = ( some.rather.elaborate.rule() and another.rule.ending_with.index[123] ) def easy_asserts(self) -> None: assert { key1: value1, key2: value2, key3: value3, key4: value4, key5: value5, key6: value6, key7: value7, key8: value8, key9: value9 } == expected, "Not what we expected" assert expected == { key1: value1, key2: value2, key3: value3, key4: value4, key5: value5, key6: value6, key7: value7, key8: value8, key9: value9 }, "Not what we expected" assert expected == { key1: value1, key2: value2, key3: value3, key4: value4, key5: value5, key6: value6, key7: value7, key8: value8, key9: value9 } def tricky_asserts(self) -> None: assert { key1: value1, key2: value2, key3: value3, key4: value4, key5: value5, key6: value6, key7: value7, key8: value8, key9: value9 } == expected( value, is_going_to_be="too long to fit in a single line", srsly=True ), "Not what we expected" assert { key1: value1, key2: value2, key3: value3, key4: value4, key5: value5, key6: value6, key7: value7, key8: value8, key9: value9 } == expected, ( "Not what we expected and the message is too long to fit in one line" ) assert expected( value, is_going_to_be="too long to fit in a single line", srsly=True ) == { key1: value1, key2: value2, key3: value3, key4: value4, key5: value5, key6: value6, key7: value7, key8: value8, key9: value9 }, "Not what we expected" assert expected == { key1: value1, key2: value2, key3: value3, key4: value4, key5: value5, key6: value6, key7: value7, key8: value8, key9: value9 }, ( "Not what we expected and the message is too long to fit in one line" " because it's too long" ) dis_c_instance_method = """\ %3d 0 LOAD_FAST 1 (x) 2 LOAD_CONST 1 (1) 4 COMPARE_OP 2 (==) 6 LOAD_FAST 0 (self) 8 STORE_ATTR 0 (x) 10 LOAD_CONST 0 (None) 12 RETURN_VALUE """ % ( _C.__init__.__code__.co_firstlineno + 1, ) assert ( expectedexpectedexpectedexpectedexpectedexpectedexpectedexpectedexpect == { key1: value1, key2: value2, key3: value3, key4: value4, key5: value5, key6: value6, key7: value7, key8: value8, key9: value9 } ) # output class C: def test(self) -> None: with patch("black.out", print): self.assertEqual( unstyle(str(report)), "1 file reformatted, 1 file failed to reformat." ) self.assertEqual( unstyle(str(report)), "1 file reformatted, 1 file left unchanged, 1 file failed to reformat.", ) self.assertEqual( unstyle(str(report)), "2 files reformatted, 1 file left unchanged, 1 file failed to" " reformat.", ) self.assertEqual( unstyle(str(report)), "2 files reformatted, 2 files left unchanged, 2 files failed to" " reformat.", ) for i in (a,): if ( # Rule 1 i % 2 == 0 # Rule 2 and i % 3 == 0 ): while ( # Just a comment call() # Another ): print(i) xxxxxxxxxxxxxxxx = Yyyy2YyyyyYyyyyy( push_manager=context.request.resource_manager, max_items_to_push=num_items, batch_size=Yyyy2YyyyYyyyyYyyy.FULL_SIZE, ).push( # Only send the first n items. items=items[:num_items] ) return ( 'Utterly failed doctest test for %s\n File "%s", line %s, in %s\n\n%s' % (test.name, test.filename, lineno, lname, err) ) def omitting_trailers(self) -> None: get_collection( hey_this_is_a_very_long_call, it_has_funny_attributes, really=True )[OneLevelIndex] get_collection( hey_this_is_a_very_long_call, it_has_funny_attributes, really=True )[OneLevelIndex][TwoLevelIndex][ThreeLevelIndex][FourLevelIndex] d[0][1][2][3][4][5][6][7][8][9][10][11][12][13][14][15][16][17][18][19][20][21][ 22 ] assignment = ( some.rather.elaborate.rule() and another.rule.ending_with.index[123] ) def easy_asserts(self) -> None: assert { key1: value1, key2: value2, key3: value3, key4: value4, key5: value5, key6: value6, key7: value7, key8: value8, key9: value9, } == expected, "Not what we expected" assert expected == { key1: value1, key2: value2, key3: value3, key4: value4, key5: value5, key6: value6, key7: value7, key8: value8, key9: value9, }, "Not what we expected" assert expected == { key1: value1, key2: value2, key3: value3, key4: value4, key5: value5, key6: value6, key7: value7, key8: value8, key9: value9, } def tricky_asserts(self) -> None: assert { key1: value1, key2: value2, key3: value3, key4: value4, key5: value5, key6: value6, key7: value7, key8: value8, key9: value9, } == expected( value, is_going_to_be="too long to fit in a single line", srsly=True ), "Not what we expected" assert { key1: value1, key2: value2, key3: value3, key4: value4, key5: value5, key6: value6, key7: value7, key8: value8, key9: value9, } == expected, ( "Not what we expected and the message is too long to fit in one line" ) assert expected( value, is_going_to_be="too long to fit in a single line", srsly=True ) == { key1: value1, key2: value2, key3: value3, key4: value4, key5: value5, key6: value6, key7: value7, key8: value8, key9: value9, }, "Not what we expected" assert expected == { key1: value1, key2: value2, key3: value3, key4: value4, key5: value5, key6: value6, key7: value7, key8: value8, key9: value9, }, ( "Not what we expected and the message is too long to fit in one line" " because it's too long" ) dis_c_instance_method = """\ %3d 0 LOAD_FAST 1 (x) 2 LOAD_CONST 1 (1) 4 COMPARE_OP 2 (==) 6 LOAD_FAST 0 (self) 8 STORE_ATTR 0 (x) 10 LOAD_CONST 0 (None) 12 RETURN_VALUE """ % ( _C.__init__.__code__.co_firstlineno + 1, ) assert ( expectedexpectedexpectedexpectedexpectedexpectedexpectedexpectedexpect == { key1: value1, key2: value2, key3: value3, key4: value4, key5: value5, key6: value6, key7: value7, key8: value8, key9: value9, } )
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/preview_long_strings__regression.py
tests/data/cases/preview_long_strings__regression.py
# flags: --unstable class A: def foo(): result = type(message)("") # Don't merge multiline (e.g. triple-quoted) strings. def foo(): query = ( """SELECT xxxxxxxxxxxxxxxxxxxx(xxx)""" """ FROM xxxxxxxxxxxxxxxx WHERE xxxxxxxxxx AND xxx <> xxxxxxxxxxxxxx()""") # There was a bug where tuples were being identified as long strings. long_tuple = ('Apple', 'Berry', 'Cherry', 'Dill', 'Evergreen', 'Fig', 'Grape', 'Harry', 'Iglu', 'Jaguar') stupid_format_method_bug = "Some really long string that just so happens to be the {} {} to force the 'format' method to hang over the line length boundary. This is pretty annoying.".format("perfect", "length") class A: def foo(): os.system("This is a regression test. xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxxx.".format("xxxxxxxxxx", "xxxxxx", "xxxxxxxxxx")) class A: def foo(): XXXXXXXXXXXX.append( ( "xxx_xxxxxxxxxx(xxxxx={}, xxxx={}, xxxxx, xxxx_xxxx_xxxxxxxxxx={})".format( xxxxx, xxxx, xxxx_xxxx_xxxxxxxxxx ), my_var, my_other_var, ) ) class A: class B: def foo(): bar( ( "[{}]: xxx_xxxxxxxxxx(xxxxx={}, xxxx={}, xxxxx={}" " xxxx_xxxx_xxxxxxxxxx={}, xxxx={})" .format(xxxx._xxxxxxxxxxxxxx, xxxxx, xxxx, xxxx_xxxx_xxxxxxxxxx, xxxxxxx) ), varX, varY, varZ, ) def foo(xxxx): for (xxx_xxxx, _xxx_xxx, _xxx_xxxxx, xxx_xxxx) in xxxx: for xxx in xxx_xxxx: assert ("x" in xxx) or ( xxx in xxx_xxx_xxxxx ), "{0} xxxxxxx xx {1}, xxx {1} xx xxx xx xxxx xx xxx xxxx: xxx xxxx {2}".format( xxx_xxxx, xxx, xxxxxx.xxxxxxx(xxx_xxx_xxxxx) ) class A: def disappearing_comment(): return ( ( # xx -x xxxxxxx xx xxx xxxxxxx. '{{xxx_xxxxxxxxxx_xxxxxxxx}} xxx xxxx' ' {} {{xxxx}} >&2' .format( "{xxxx} {xxxxxx}" if xxxxx.xx_xxxxxxxxxx else ( # Disappearing Comment "--xxxxxxx --xxxxxx=x --xxxxxx-xxxxx=xxxxxx" " --xxxxxx-xxxx=xxxxxxxxxxx.xxx" ) ) ), (x, y, z), ) class A: class B: def foo(): xxxxx_xxxx( xx, "\t" "@xxxxxx '{xxxx_xxx}\t' > {xxxxxx_xxxx}.xxxxxxx;" "{xxxx_xxx} >> {xxxxxx_xxxx}.xxxxxxx 2>&1; xx=$$?;" "xxxx $$xx" .format(xxxx_xxx=xxxx_xxxxxxx, xxxxxx_xxxx=xxxxxxx + "/" + xxxx_xxx_xxxx, x=xxx_xxxxx_xxxxx_xxx), x, y, z, ) func_call_where_string_arg_has_method_call_and_bad_parens( ( "A long string with {}. This string is so long that it is ridiculous. It can't fit on one line at alllll.".format("formatting") ), ) func_call_where_string_arg_has_old_fmt_and_bad_parens( ( "A long string with {}. This string is so long that it is ridiculous. It can't fit on one line at alllll." % "formatting" ), ) func_call_where_string_arg_has_old_fmt_and_bad_parens( ( "A long string with {}. This {} is so long that it is ridiculous. It can't fit on one line at alllll." % ("formatting", "string") ), ) class A: def append(self): if True: xxxx.xxxxxxx.xxxxx( ('xxxxxxxxxx xxxx xx xxxxxx(%x) xx %x xxxx xx xxx %x.xx' % (len(self) + 1, xxxx.xxxxxxxxxx, xxxx.xxxxxxxxxx)) + (' %.3f (%s) to %.3f (%s).\n' % (xxxx.xxxxxxxxx, xxxx.xxxxxxxxxxxxxx(xxxx.xxxxxxxxx), x, xxxx.xxxxxxxxxxxxxx( xx) ))) class A: def foo(): some_func_call( 'xxxxxxxxxx', ( "xx {xxxxxxxxxxx}/xxxxxxxxxxx.xxx xxxx.xxx && xxxxxx -x " "\"xxxx xxxxxxx xxxxxx xxxx; xxxx xxxxxx_xxxxx xxxxxx xxxx; " "xxxx.xxxx_xxxxxx(['xxxx.xxx'], xxxx.xxxxxxx().xxxxxxxxxx)\" " ), None, ('xxxxxxxxxxx',), ), class A: def foo(): some_func_call( ( "xx {xxxxxxxxxxx}/xxxxxxxxxxx.xxx xxxx.xxx && xxxxxx -x " "xxxx, ('xxxxxxx xxxxxx xxxx, xxxx') xxxxxx_xxxxx xxxxxx xxxx; " "xxxx.xxxx_xxxxxx(['xxxx.xxx'], xxxx.xxxxxxx().xxxxxxxxxx)\" " ), None, ('xxxxxxxxxxx',), ), xxxxxxx = { 'xx' : 'xxxx xxxxxxx xxxxxxxxx -x xxx -x /xxx/{0} -x xxx,xxx -xx {1} \ -xx {1} -xx xxx=xxx_xxxx,xxx_xx,xxx_xxx,xxx_xxxx,xxx_xx,xxx_xxx |\ xxxxxx -x xxxxxxxx -x xxxxxxxx -x', 'xx' : 'xxxx xxxxxxx xxxxxxxxx -x xxx -x /xxx/{0} -x xxx,xxx -xx {1} \ -xx {1} -xx xxx=xxx_xxxx_xxx_xxxx,xxx_xx_xxx_xxxx,xxx_xxxx_xxx_xxxx,\ xxx_xx_xxxx_xxxx,xxx_xxx_xxxx,xxx_xxx_xxxx xxxx=xxx | xxxxxx -x xxxxxxxx -x xxxxxxxx -x' } class A: def foo(self): if True: xxxxx_xxxxxxxxxxxx('xxx xxxxxx xxx xxxxxxxxx.xx xx xxxxxxxx. xxx xxxxxxxxxxxxx.xx xxxxxxx ' + 'xx xxxxxx xxxxxx xxxxxx xx xxxxxxx xxx xxx ${0} xx x xxxxxxxx xxxxx'.xxxxxx(xxxxxx_xxxxxx_xxx)) class A: class B: def foo(): row = { 'xxxxxxxxxxxxxxx' : xxxxxx_xxxxx_xxxx, # 'xxxxxxxxxxxxxxxxxxxxxxx' # 'xxxxxxxxxxxxxxxxxxxxxx' # 'xxxxxxxxxxxxxxxxxx' # 'xxxxxxxxxxxxxxxxx' 'xxxxxxxxxx' : xxxxx_xxxxx, } class A: def xxxx_xxx_xx_xxxxxxxxxx_xxxx_xxxxxxxxx(xxxx): xxxxxxxx = [ xxxxxxxxxxxxxxxx( 'xxxx', xxxxxxxxxxx={ 'xxxx' : 1.0, }, xxxxxx={'xxxxxx 1' : xxxxxx(xxxx='xxxxxx 1', xxxxxx=600.0)}, xxxxxxxx_xxxxxxx=0.0, ), xxxxxxxxxxxxxxxx( 'xxxxxxx', xxxxxxxxxxx={ 'xxxx' : 1.0, }, xxxxxx={'xxxxxx 1' : xxxxxx(xxxx='xxxxxx 1', xxxxxx=200.0)}, xxxxxxxx_xxxxxxx=0.0, ), xxxxxxxxxxxxxxxx( 'xxxx', ), ] some_dictionary = { 'xxxxx006': ['xxx-xxx xxxxx3xxxx1xx2xxxxxxxxxxxxxx0xx6xxxxxxxxxx2xxxxxx9xxxxxxxxxx0xxxxx1xxx2x/xx9xx6+x+xxxxxxxxxxxxxx4xxxxxxxxxxxxxxxxxxxxx43xxx2xx2x4x++xxx6xxxxxxxxx+xxxxx/xx9x+xxxxxxxxxxxxxx8x15xxxxxxxxxxxxxxxxx82xx/xxxxxxxxxxxxxx/x5xxxxxxxxxxxxxx6xxxxxx74x4/xxx4x+xxxxxxxxx2xxxxxxxx87xxxxx4xxxxxxxx3xx0xxxxx4xxx1xx9xx5xxxxxxx/xxxxx5xx6xx4xxxx1x/x2xxxxxxxxxxxx64xxxxxxx1x0xx5xxxxxxxxxxxxxx== xxxxx000 xxxxxxxxxx\n', 'xxx-xxx xxxxx3xxxx1xx2xxxxxxxxxxxxxx6xxxxxxxxxxxxxx9xxxxxxxxxxxxx3xxx9xxxxxxxxxxxxxxxx0xxxxxxxxxxxxxxxxx2xxxx2xxx6xxxxx/xx54xxxxxxxxx4xxx3xxxxxx9xx3xxxxx39xxxxxxxxx5xx91xxxx7xxxxxx8xxxxxxxxxxxxxxxx9xxx93xxxxxxxxxxxxxxxxx7xxx8xx8xx4/x1xxxxx1x3xxxxxxxxxxxxx3xxxxxx9xx4xx4x7xxxxxxxxxxxxx1xxxxxxxxx7xxxxxxxxxxxxxx4xx6xxxxxxxxx9xxx7xxxx2xxxxxxxxxxxxxxxxxxxxxx8xxxxxxxxxxxxxxxxxxxx6xx== xxxxx010 xxxxxxxxxx\n'], 'xxxxx016': ['xxx-xxx xxxxx3xxxx1xx2xxxxxxxxxxxxxx0xx6xxxxxxxxxx2xxxxxx9xxxxxxxxxx0xxxxx1xxx2x/xx9xx6+x+xxxxxxxxxxxxxx4xxxxxxxxxxxxxxxxxxxxx43xxx2xx2x4x++xxx6xxxxxxxxx+xxxxx/xx9x+xxxxxxxxxxxxxx8x15xxxxxxxxxxxxxxxxx82xx/xxxxxxxxxxxxxx/x5xxxxxxxxxxxxxx6xxxxxx74x4/xxx4x+xxxxxxxxx2xxxxxxxx87xxxxx4xxxxxxxx3xx0xxxxx4xxx1xx9xx5xxxxxxx/xxxxx5xx6xx4xxxx1x/x2xxxxxxxxxxxx64xxxxxxx1x0xx5xxxxxxxxxxxxxx== xxxxx000 xxxxxxxxxx\n', 'xxx-xxx xxxxx3xxxx1xx2xxxxxxxxxxxxxx6xxxxxxxxxxxxxx9xxxxxxxxxxxxx3xxx9xxxxxxxxxxxxxxxx0xxxxxxxxxxxxxxxxx2xxxx2xxx6xxxxx/xx54xxxxxxxxx4xxx3xxxxxx9xx3xxxxx39xxxxxxxxx5xx91xxxx7xxxxxx8xxxxxxxxxxxxxxxx9xxx93xxxxxxxxxxxxxxxxx7xxx8xx8xx4/x1xxxxx1x3xxxxxxxxxxxxx3xxxxxx9xx4xx4x7xxxxxxxxxxxxx1xxxxxxxxx7xxxxxxxxxxxxxx4xx6xxxxxxxxx9xxx7xxxx2xxxxxxxxxxxxxxxxxxxxxx8xxxxxxxxxxxxxxxxxxxx6xx== xxxxx010 xxxxxxxxxx\n'] } def foo(): xxx_xxx = ( 'xxxx xxx xxxxxxxx_xxxx xx "xxxxxxxxxx".' '\n xxx: xxxxxx xxxxxxxx_xxxx=xxxxxxxxxx' ) # xxxx xxxxxxxxxx xxxx xx xxxx xx xxx xxxxxxxx xxxxxx xxxxx. some_tuple = ("some string", "some string" " which should be joined") some_commented_string = ( # This comment stays at the top. "This string is long but not so long that it needs hahahah toooooo be so greatttt" " {} that I just can't think of any more good words to say about it at" " allllllllllll".format("ha") # comments here are fine ) some_commented_string = ( "This string is long but not so long that it needs hahahah toooooo be so greatttt" # But these " {} that I just can't think of any more good words to say about it at" # comments will stay " allllllllllll".format("ha") # comments here are fine ) lpar_and_rpar_have_comments = func_call( # LPAR Comment "Long really ridiculous type of string that shouldn't really even exist at all. I mean commmme onnn!!!", # Comma Comment ) # RPAR Comment cmd_fstring = ( f"sudo -E deluge-console info --detailed --sort-reverse=time_added " f"{'' if ID is None else ID} | perl -nE 'print if /^{field}:/'" ) cmd_fstring = f"sudo -E deluge-console info --detailed --sort-reverse=time_added {'' if ID is None else ID} | perl -nE 'print if /^{field}:/'" cmd_fstring = f"sudo -E deluge-console info --detailed --sort-reverse=time_added {'{{}}' if ID is None else ID} | perl -nE 'print if /^{field}:/'" cmd_fstring = f"sudo -E deluge-console info --detailed --sort-reverse=time_added {{'' if ID is None else ID}} | perl -nE 'print if /^{field}:/'" fstring = f"This string really doesn't need to be an {{{{fstring}}}}, but this one most certainly, absolutely {does}." fstring = ( f"We have to remember to escape {braces}." " Like {these}." f" But not {this}." ) class A: class B: def foo(): st_error = STError( f"This string ({string_leaf.value}) appears to be pointless (i.e. has" " no parent)." ) def foo(): user_regex = _lazy_re_compile( r"(^[-!#$%&'*+/=?^_`{}|~0-9A-Z]+(\.[-!#$%&'*+/=?^_`{}|~0-9A-Z]+)*\Z" # dot-atom r'|^"([\001-\010\013\014\016-\037!#-\[\]-\177]|\\[\001-\011\013\014\016-\177])*"\Z)', # quoted-string re.IGNORECASE) def foo(): user_regex = _lazy_re_compile( "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" # dot-atom 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', # quoted-string xyz ) def foo(): user_regex = _lazy_re_compile( "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" # dot-atom 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', # quoted-string xyz ) class A: class B: def foo(): if not hasattr(module, name): raise ValueError( "Could not find object %s in %s.\n" "Please note that you cannot serialize things like inner " "classes. Please move the object into the main module " "body to use migrations.\n" "For more information, see " "https://docs.djangoproject.com/en/%s/topics/migrations/#serializing-values" % (name, module_name, get_docs_version())) class A: class B: def foo(): if not hasattr(module, name): raise ValueError( "Could not find object %s in %s.\nPlease note that you cannot serialize things like inner classes. Please move the object into the main module body to use migrations.\nFor more information, see https://docs.djangoproject.com/en/%s/topics/migrations/#serializing-values" % (name, module_name, get_docs_version())) x = ( "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" ) class Step(StepBase): def who(self): self.cmd = 'SR AAAA-CORRECT NAME IS {last_name} {first_name}{middle_name} {title}/P{passenger_association}'.format( last_name=last_name, first_name=first_name, middle_name=middle_name, title=title, passenger_association=passenger_association, ) xxxxxxx_xxxxxx_xxxxxxx = xxx( [ xxxxxxxxxxxx( xxxxxx_xxxxxxx=( '((x.aaaaaaaaa = "xxxxxx.xxxxxxxxxxxxxxxxxxxxx") || (x.xxxxxxxxx = "xxxxxxxxxxxx")) && ' # xxxxx xxxxxxxxxxxx xxxx xxx (xxxxxxxxxxxxxxxx) xx x xxxxxxxxx xx xxxxxx. "(x.bbbbbbbbbbbb.xxx != " '"xxx:xxx:xxx::cccccccccccc:xxxxxxx-xxxx/xxxxxxxxxxx/xxxxxxxxxxxxxxxxx") && ' ) ) ] ) if __name__ == "__main__": for i in range(4, 8): cmd = ( r"for pid in $(ps aux | grep paster | grep -v grep | grep '\-%d' | awk '{print $2}'); do kill $pid; done" % (i) ) def A(): def B(): def C(): def D(): def E(): def F(): def G(): assert ( c_float(val[0][0] / val[0][1]).value == c_float(value[0][0] / value[0][1]).value ), "%s didn't roundtrip" % tag class xxxxxxxxxxxxxxxxxxxxx(xxxx.xxxxxxxxxxxxx): def xxxxxxx_xxxxxx(xxxx): assert xxxxxxx_xxxx in [ x.xxxxx.xxxxxx.xxxxx.xxxxxx, x.xxxxx.xxxxxx.xxxxx.xxxx, ], ("xxxxxxxxxxx xxxxxxx xxxx (xxxxxx xxxx) %x xxx xxxxx" % xxxxxxx_xxxx) value.__dict__[ key ] = "test" # set some Thrift field to non-None in the struct aa bb cc dd ee RE_ONE_BACKSLASH = { "asdf_hjkl_jkl": re.compile( r"(?<!([0-9]\ ))(?<=(^|\ ))([A-Z]+(\ )?|[0-9](\ )|[a-z](\ )){4,7}([A-Z]|[0-9]|[a-z])($|\b)(?!(\ ?([0-9]\ )|(\.)))" ), } RE_TWO_BACKSLASHES = { "asdf_hjkl_jkl": re.compile( r"(?<!([0-9]\ ))(?<=(^|\ ))([A-Z]+(\ )?|[0-9](\ )|[a-z](\\ )){4,7}([A-Z]|[0-9]|[a-z])($|\b)(?!(\ ?([0-9]\ )|(\.)))" ), } RE_THREE_BACKSLASHES = { "asdf_hjkl_jkl": re.compile( r"(?<!([0-9]\ ))(?<=(^|\ ))([A-Z]+(\ )?|[0-9](\ )|[a-z](\\\ )){4,7}([A-Z]|[0-9]|[a-z])($|\b)(?!(\ ?([0-9]\ )|(\.)))" ), } # We do NOT split on f-string expressions. print(f"Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam. {[f'{i}' for i in range(10)]}") x = f"This is a long string which contains an f-expr that should not split {{{[i for i in range(5)]}}}." # The parens should NOT be removed in this case. ( "my very long string that should get formatted if I'm careful to make sure it goes" " over 88 characters which it has now" ) # The parens should NOT be removed in this case. ( "my very long string that should get formatted if I'm careful to make sure it goes over 88 characters which" " it has now" ) # The parens should NOT be removed in this case. ( "my very long string" " that should get formatted" " if I'm careful to make sure" " it goes over 88 characters which" " it has now" ) def _legacy_listen_examples(): text += ( " \"listen for the '%(event_name)s' event\"\n" "\n # ... (event logic logic logic) ...\n" % { "since": since, } ) class X: async def foo(self): msg = "" for candidate in CANDIDATES: msg += ( "**{candidate.object_type} {candidate.rev}**" " - {candidate.description}\n" ) temp_msg = ( f"{f'{humanize_number(pos)}.': <{pound_len+2}} " f"{balance: <{bal_len + 5}} " f"<<{author.display_name}>>\n" ) assert str(suffix_arr) == ( "['$', 'angaroo$', 'angrykangaroo$', 'aroo$', 'garoo$', " "'grykangaroo$', 'kangaroo$', 'ngaroo$', 'ngrykangaroo$', " "'o$', 'oo$', 'roo$', 'rykangaroo$', 'ykangaroo$']" ) assert str(suffix_arr) != ( "['$', 'angaroo$', 'angrykangaroo$', 'aroo$', 'garoo$', " "'grykangaroo$', 'kangaroo$', 'ngaroo$', 'ngrykangaroo$', " "'o$', 'oo$', 'roo$', 'rykangaroo$', 'ykangaroo$']" ) assert str(suffix_arr) <= ( "['$', 'angaroo$', 'angrykangaroo$', 'aroo$', 'garoo$', " "'grykangaroo$', 'kangaroo$', 'ngaroo$', 'ngrykangaroo$', " "'o$', 'oo$', 'roo$', 'rykangaroo$', 'ykangaroo$']" ) assert str(suffix_arr) >= ( "['$', 'angaroo$', 'angrykangaroo$', 'aroo$', 'garoo$', " "'grykangaroo$', 'kangaroo$', 'ngaroo$', 'ngrykangaroo$', " "'o$', 'oo$', 'roo$', 'rykangaroo$', 'ykangaroo$']" ) assert str(suffix_arr) < ( "['$', 'angaroo$', 'angrykangaroo$', 'aroo$', 'garoo$', " "'grykangaroo$', 'kangaroo$', 'ngaroo$', 'ngrykangaroo$', " "'o$', 'oo$', 'roo$', 'rykangaroo$', 'ykangaroo$']" ) assert str(suffix_arr) > ( "['$', 'angaroo$', 'angrykangaroo$', 'aroo$', 'garoo$', " "'grykangaroo$', 'kangaroo$', 'ngaroo$', 'ngrykangaroo$', " "'o$', 'oo$', 'roo$', 'rykangaroo$', 'ykangaroo$']" ) assert str(suffix_arr) in "['$', 'angaroo$', 'angrykangaroo$', 'aroo$', 'garoo$', 'grykangaroo$', 'kangaroo$', 'ngaroo$', 'ngrykangaroo$', 'o$', 'oo$', 'roo$', 'rykangaroo$', 'ykangaroo$']" assert str(suffix_arr) not in "['$', 'angaroo$', 'angrykangaroo$', 'aroo$', 'garoo$', 'grykangaroo$', 'kangaroo$', 'ngaroo$', 'ngrykangaroo$', 'o$', 'oo$', 'roo$', 'rykangaroo$', 'ykangaroo$']" message = ( f"1. Go to Google Developers Console and log in with your Google account." "(https://console.developers.google.com/)" "2. You should be prompted to create a new project (name does not matter)." "3. Click on Enable APIs and Services at the top." "4. In the list of APIs choose or search for YouTube Data API v3 and " "click on it. Choose Enable." "5. Click on Credentials on the left navigation bar." "6. Click on Create Credential at the top." '7. At the top click the link for "API key".' "8. No application restrictions are needed. Click Create at the bottom." "9. You now have a key to add to `{prefix}set api youtube api_key`" ) message = ( f"1. Go to Google Developers Console and log in with your Google account." "(https://console.developers.google.com/)" "2. You should be prompted to create a new project (name does not matter)." f"3. Click on Enable APIs and Services at the top." "4. In the list of APIs choose or search for YouTube Data API v3 and " "click on it. Choose Enable." f"5. Click on Credentials on the left navigation bar." "6. Click on Create Credential at the top." '7. At the top click the link for "API key".' "8. No application restrictions are needed. Click Create at the bottom." "9. You now have a key to add to `{prefix}set api youtube api_key`" ) message = ( f"1. Go to Google Developers Console and log in with your Google account." "(https://console.developers.google.com/)" "2. You should be prompted to create a new project (name does not matter)." f"3. Click on Enable APIs and Services at the top." "4. In the list of APIs choose or search for YouTube Data API v3 and " "click on it. Choose Enable." f"5. Click on Credentials on the left navigation bar." "6. Click on Create Credential at the top." '7. At the top click the link for "API key".' "8. No application restrictions are needed. Click Create at the bottom." f"9. You now have a key to add to `{prefix}set api youtube api_key`" ) # It shouldn't matter if the string prefixes are capitalized. temp_msg = ( F"{F'{humanize_number(pos)}.': <{pound_len+2}} " F"{balance: <{bal_len + 5}} " F"<<{author.display_name}>>\n" ) fstring = ( F"We have to remember to escape {braces}." " Like {these}." F" But not {this}." ) welcome_to_programming = R"hello," R" world!" fstring = F"f-strings definitely make things more {difficult} than they need to be for {{black}}. But boy they sure are handy. The problem is that some lines will need to have the 'f' whereas others do not. This {line}, for example, needs one." x = F"This is a long string which contains an f-expr that should not split {{{[i for i in range(5)]}}}." x = ( "\N{BLACK RIGHT-POINTING TRIANGLE WITH DOUBLE VERTICAL BAR}\N{VARIATION SELECTOR-16}" ) xxxxxx_xxx_xxxx_xx_xxxxx_xxxxxxxx_xxxxxxxx_xxxxxxxxxx_xxxx_xxxx_xxxxx = xxxx.xxxxxx.xxxxxxxxx.xxxxxxxxxxxxxxxxxxxx( xx_xxxxxx={ "x3_xxxxxxxx": "xxx3_xxxxx_xxxxxxxx_xxxxxxxx_xxxxxxxxxx_xxxxxxxx_xxxxxx_xxxxxxx", }, ) # Regression test for https://github.com/psf/black/issues/3117. some_dict = { "something_something": r"Lorem ipsum dolor sit amet, an sed convenire eloquentiam \t" r"signiferumque, duo ea vocibus consetetur scriptorem. Facer \t", } # Regression test for https://github.com/psf/black/issues/3459. xxxx( empty_str_as_first_split='' f'xxxxxxx {xxxxxxxxxx} xxx xxxxxxxxxx xxxxx xxx xxx xx ' 'xxxxx xxxxxxxxx xxxxxxx, xxx xxxxxxxxxxx xxx xxxxx. ' f'xxxxxxxxxxxxx xxxx xx xxxxxxxxxx. xxxxx: {x.xxx}', empty_u_str_as_first_split=u'' f'xxxxxxx {xxxxxxxxxx} xxx xxxxxxxxxx xxxxx xxx xxx xx ' 'xxxxx xxxxxxxxx xxxxxxx, xxx xxxxxxxxxxx xxx xxxxx. ' f'xxxxxxxxxxxxx xxxx xx xxxxxxxxxx. xxxxx: {x.xxx}', ) # Regression test for https://github.com/psf/black/issues/3455. a_dict = { "/this/is/a/very/very/very/very/very/very/very/very/very/very/long/key/without/spaces": # And there is a comment before the value ("item1", "item2", "item3"), } # Regression test for https://github.com/psf/black/issues/3506. # Regressed again by https://github.com/psf/black/pull/4498 s = ( "With single quote: ' " f" {my_dict['foo']}" ' With double quote: " ' f' {my_dict["bar"]}' ) s = f'Lorem Ipsum is simply dummy text of the printing and typesetting industry:\'{my_dict["foo"]}\'' # output class A: def foo(): result = type(message)("") # Don't merge multiline (e.g. triple-quoted) strings. def foo(): query = ( """SELECT xxxxxxxxxxxxxxxxxxxx(xxx)""" """ FROM xxxxxxxxxxxxxxxx WHERE xxxxxxxxxx AND xxx <> xxxxxxxxxxxxxx()""" ) # There was a bug where tuples were being identified as long strings. long_tuple = ( "Apple", "Berry", "Cherry", "Dill", "Evergreen", "Fig", "Grape", "Harry", "Iglu", "Jaguar", ) stupid_format_method_bug = ( "Some really long string that just so happens to be the {} {} to force the 'format'" " method to hang over the line length boundary. This is pretty annoying.".format( "perfect", "length" ) ) class A: def foo(): os.system( "This is a regression test. xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx" " xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx" " xxxx.".format("xxxxxxxxxx", "xxxxxx", "xxxxxxxxxx") ) class A: def foo(): XXXXXXXXXXXX.append(( "xxx_xxxxxxxxxx(xxxxx={}, xxxx={}, xxxxx, xxxx_xxxx_xxxxxxxxxx={})".format( xxxxx, xxxx, xxxx_xxxx_xxxxxxxxxx ), my_var, my_other_var, )) class A: class B: def foo(): bar( "[{}]: xxx_xxxxxxxxxx(xxxxx={}, xxxx={}, xxxxx={}" " xxxx_xxxx_xxxxxxxxxx={}, xxxx={})".format( xxxx._xxxxxxxxxxxxxx, xxxxx, xxxx, xxxx_xxxx_xxxxxxxxxx, xxxxxxx ), varX, varY, varZ, ) def foo(xxxx): for xxx_xxxx, _xxx_xxx, _xxx_xxxxx, xxx_xxxx in xxxx: for xxx in xxx_xxxx: assert ("x" in xxx) or (xxx in xxx_xxx_xxxxx), ( "{0} xxxxxxx xx {1}, xxx {1} xx xxx xx xxxx xx xxx xxxx: xxx xxxx {2}" .format(xxx_xxxx, xxx, xxxxxx.xxxxxxx(xxx_xxx_xxxxx)) ) class A: def disappearing_comment(): return ( ( # xx -x xxxxxxx xx xxx xxxxxxx. "{{xxx_xxxxxxxxxx_xxxxxxxx}} xxx xxxx {} {{xxxx}} >&2".format( "{xxxx} {xxxxxx}" if xxxxx.xx_xxxxxxxxxx else ( # Disappearing Comment "--xxxxxxx --xxxxxx=x --xxxxxx-xxxxx=xxxxxx" " --xxxxxx-xxxx=xxxxxxxxxxx.xxx" ) ) ), (x, y, z), ) class A: class B: def foo(): xxxxx_xxxx( xx, "\t" "@xxxxxx '{xxxx_xxx}\t' > {xxxxxx_xxxx}.xxxxxxx;" "{xxxx_xxx} >> {xxxxxx_xxxx}.xxxxxxx 2>&1; xx=$$?;" "xxxx $$xx".format( xxxx_xxx=xxxx_xxxxxxx, xxxxxx_xxxx=xxxxxxx + "/" + xxxx_xxx_xxxx, x=xxx_xxxxx_xxxxx_xxx, ), x, y, z, ) func_call_where_string_arg_has_method_call_and_bad_parens( "A long string with {}. This string is so long that it is ridiculous. It can't fit" " on one line at alllll.".format("formatting"), ) func_call_where_string_arg_has_old_fmt_and_bad_parens( "A long string with {}. This string is so long that it is ridiculous. It can't fit" " on one line at alllll." % "formatting", ) func_call_where_string_arg_has_old_fmt_and_bad_parens( "A long string with {}. This {} is so long that it is ridiculous. It can't fit on" " one line at alllll." % ("formatting", "string"), ) class A: def append(self): if True: xxxx.xxxxxxx.xxxxx( "xxxxxxxxxx xxxx xx xxxxxx(%x) xx %x xxxx xx xxx %x.xx" % (len(self) + 1, xxxx.xxxxxxxxxx, xxxx.xxxxxxxxxx) + " %.3f (%s) to %.3f (%s).\n" % ( xxxx.xxxxxxxxx, xxxx.xxxxxxxxxxxxxx(xxxx.xxxxxxxxx), x, xxxx.xxxxxxxxxxxxxx(xx), ) ) class A: def foo(): some_func_call( "xxxxxxxxxx", "xx {xxxxxxxxxxx}/xxxxxxxxxxx.xxx xxxx.xxx && xxxxxx -x " '"xxxx xxxxxxx xxxxxx xxxx; xxxx xxxxxx_xxxxx xxxxxx xxxx; ' "xxxx.xxxx_xxxxxx(['xxxx.xxx'], xxxx.xxxxxxx().xxxxxxxxxx)\" ", None, ("xxxxxxxxxxx",), ), class A: def foo(): some_func_call( "xx {xxxxxxxxxxx}/xxxxxxxxxxx.xxx xxxx.xxx && xxxxxx -x " "xxxx, ('xxxxxxx xxxxxx xxxx, xxxx') xxxxxx_xxxxx xxxxxx xxxx; " "xxxx.xxxx_xxxxxx(['xxxx.xxx'], xxxx.xxxxxxx().xxxxxxxxxx)\" ", None, ("xxxxxxxxxxx",), ), xxxxxxx = { "xx": ( "xxxx xxxxxxx xxxxxxxxx -x xxx -x /xxx/{0} -x xxx,xxx -xx {1} -xx {1} -xx" " xxx=xxx_xxxx,xxx_xx,xxx_xxx,xxx_xxxx,xxx_xx,xxx_xxx | xxxxxx -x xxxxxxxx -x" " xxxxxxxx -x" ), "xx": ( "xxxx xxxxxxx xxxxxxxxx -x xxx -x /xxx/{0} -x xxx,xxx -xx {1} -xx {1} -xx" " xxx=xxx_xxxx_xxx_xxxx,xxx_xx_xxx_xxxx,xxx_xxxx_xxx_xxxx,xxx_xx_xxxx_xxxx,xxx_xxx_xxxx,xxx_xxx_xxxx" " xxxx=xxx | xxxxxx -x xxxxxxxx -x xxxxxxxx -x" ), } class A: def foo(self): if True: xxxxx_xxxxxxxxxxxx( "xxx xxxxxx xxx xxxxxxxxx.xx xx xxxxxxxx. xxx xxxxxxxxxxxxx.xx" " xxxxxxx " + "xx xxxxxx xxxxxx xxxxxx xx xxxxxxx xxx xxx ${0} xx x xxxxxxxx xxxxx" .xxxxxx(xxxxxx_xxxxxx_xxx) ) class A: class B: def foo(): row = { "xxxxxxxxxxxxxxx": xxxxxx_xxxxx_xxxx, # 'xxxxxxxxxxxxxxxxxxxxxxx' # 'xxxxxxxxxxxxxxxxxxxxxx' # 'xxxxxxxxxxxxxxxxxx' # 'xxxxxxxxxxxxxxxxx' "xxxxxxxxxx": xxxxx_xxxxx, } class A: def xxxx_xxx_xx_xxxxxxxxxx_xxxx_xxxxxxxxx(xxxx): xxxxxxxx = [ xxxxxxxxxxxxxxxx( "xxxx", xxxxxxxxxxx={ "xxxx": 1.0, }, xxxxxx={"xxxxxx 1": xxxxxx(xxxx="xxxxxx 1", xxxxxx=600.0)}, xxxxxxxx_xxxxxxx=0.0, ), xxxxxxxxxxxxxxxx( "xxxxxxx", xxxxxxxxxxx={ "xxxx": 1.0, }, xxxxxx={"xxxxxx 1": xxxxxx(xxxx="xxxxxx 1", xxxxxx=200.0)}, xxxxxxxx_xxxxxxx=0.0, ), xxxxxxxxxxxxxxxx( "xxxx", ), ] some_dictionary = { "xxxxx006": [ ( "xxx-xxx" " xxxxx3xxxx1xx2xxxxxxxxxxxxxx0xx6xxxxxxxxxx2xxxxxx9xxxxxxxxxx0xxxxx1xxx2x/xx9xx6+x+xxxxxxxxxxxxxx4xxxxxxxxxxxxxxxxxxxxx43xxx2xx2x4x++xxx6xxxxxxxxx+xxxxx/xx9x+xxxxxxxxxxxxxx8x15xxxxxxxxxxxxxxxxx82xx/xxxxxxxxxxxxxx/x5xxxxxxxxxxxxxx6xxxxxx74x4/xxx4x+xxxxxxxxx2xxxxxxxx87xxxxx4xxxxxxxx3xx0xxxxx4xxx1xx9xx5xxxxxxx/xxxxx5xx6xx4xxxx1x/x2xxxxxxxxxxxx64xxxxxxx1x0xx5xxxxxxxxxxxxxx==" " xxxxx000 xxxxxxxxxx\n" ), ( "xxx-xxx" " xxxxx3xxxx1xx2xxxxxxxxxxxxxx6xxxxxxxxxxxxxx9xxxxxxxxxxxxx3xxx9xxxxxxxxxxxxxxxx0xxxxxxxxxxxxxxxxx2xxxx2xxx6xxxxx/xx54xxxxxxxxx4xxx3xxxxxx9xx3xxxxx39xxxxxxxxx5xx91xxxx7xxxxxx8xxxxxxxxxxxxxxxx9xxx93xxxxxxxxxxxxxxxxx7xxx8xx8xx4/x1xxxxx1x3xxxxxxxxxxxxx3xxxxxx9xx4xx4x7xxxxxxxxxxxxx1xxxxxxxxx7xxxxxxxxxxxxxx4xx6xxxxxxxxx9xxx7xxxx2xxxxxxxxxxxxxxxxxxxxxx8xxxxxxxxxxxxxxxxxxxx6xx==" " xxxxx010 xxxxxxxxxx\n" ), ], "xxxxx016": [ ( "xxx-xxx" " xxxxx3xxxx1xx2xxxxxxxxxxxxxx0xx6xxxxxxxxxx2xxxxxx9xxxxxxxxxx0xxxxx1xxx2x/xx9xx6+x+xxxxxxxxxxxxxx4xxxxxxxxxxxxxxxxxxxxx43xxx2xx2x4x++xxx6xxxxxxxxx+xxxxx/xx9x+xxxxxxxxxxxxxx8x15xxxxxxxxxxxxxxxxx82xx/xxxxxxxxxxxxxx/x5xxxxxxxxxxxxxx6xxxxxx74x4/xxx4x+xxxxxxxxx2xxxxxxxx87xxxxx4xxxxxxxx3xx0xxxxx4xxx1xx9xx5xxxxxxx/xxxxx5xx6xx4xxxx1x/x2xxxxxxxxxxxx64xxxxxxx1x0xx5xxxxxxxxxxxxxx==" " xxxxx000 xxxxxxxxxx\n" ), ( "xxx-xxx" " xxxxx3xxxx1xx2xxxxxxxxxxxxxx6xxxxxxxxxxxxxx9xxxxxxxxxxxxx3xxx9xxxxxxxxxxxxxxxx0xxxxxxxxxxxxxxxxx2xxxx2xxx6xxxxx/xx54xxxxxxxxx4xxx3xxxxxx9xx3xxxxx39xxxxxxxxx5xx91xxxx7xxxxxx8xxxxxxxxxxxxxxxx9xxx93xxxxxxxxxxxxxxxxx7xxx8xx8xx4/x1xxxxx1x3xxxxxxxxxxxxx3xxxxxx9xx4xx4x7xxxxxxxxxxxxx1xxxxxxxxx7xxxxxxxxxxxxxx4xx6xxxxxxxxx9xxx7xxxx2xxxxxxxxxxxxxxxxxxxxxx8xxxxxxxxxxxxxxxxxxxx6xx==" " xxxxx010 xxxxxxxxxx\n" ), ], } def foo(): xxx_xxx = ( # xxxx xxxxxxxxxx xxxx xx xxxx xx xxx xxxxxxxx xxxxxx xxxxx. 'xxxx xxx xxxxxxxx_xxxx xx "xxxxxxxxxx".\n xxx: xxxxxx xxxxxxxx_xxxx=xxxxxxxxxx' ) some_tuple = ("some string", "some string which should be joined") some_commented_string = ( # This comment stays at the top. "This string is long but not so long that it needs hahahah toooooo be so greatttt" " {} that I just can't think of any more good words to say about it at" " allllllllllll".format("ha") # comments here are fine ) some_commented_string = ( "This string is long but not so long that it needs hahahah toooooo be so greatttt" # But these " {} that I just can't think of any more good words to say about it at" # comments will stay " allllllllllll".format("ha") # comments here are fine ) lpar_and_rpar_have_comments = func_call( # LPAR Comment "Long really ridiculous type of string that shouldn't really even exist at all. I" " mean commmme onnn!!!", # Comma Comment ) # RPAR Comment cmd_fstring = ( "sudo -E deluge-console info --detailed --sort-reverse=time_added " f"{'' if ID is None else ID} | perl -nE 'print if /^{field}:/'" ) cmd_fstring = ( "sudo -E deluge-console info --detailed --sort-reverse=time_added" f" {'' if ID is None else ID} | perl -nE 'print if /^{field}:/'" ) cmd_fstring = (
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
true
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/preview_fstring.py
tests/data/cases/preview_fstring.py
# flags: --unstable f"{''=}" f'{""=}'
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/long_strings__type_annotations.py
tests/data/cases/long_strings__type_annotations.py
def func( arg1, arg2, ) -> Set["this_is_a_very_long_module_name.AndAVeryLongClasName" ".WithAVeryVeryVeryVeryVeryLongSubClassName"]: pass def func( argument: ( "VeryLongClassNameWithAwkwardGenericSubtype[int] |" "VeryLongClassNameWithAwkwardGenericSubtype[str]" ), ) -> ( "VeryLongClassNameWithAwkwardGenericSubtype[int] |" "VeryLongClassNameWithAwkwardGenericSubtype[str]" ): pass def func( argument: ( "int |" "str" ), ) -> Set["int |" " str"]: pass # output def func( arg1, arg2, ) -> Set[ "this_is_a_very_long_module_name.AndAVeryLongClasName" ".WithAVeryVeryVeryVeryVeryLongSubClassName" ]: pass def func( argument: ( "VeryLongClassNameWithAwkwardGenericSubtype[int] |" "VeryLongClassNameWithAwkwardGenericSubtype[str]" ), ) -> ( "VeryLongClassNameWithAwkwardGenericSubtype[int] |" "VeryLongClassNameWithAwkwardGenericSubtype[str]" ): pass def func( argument: "int |" "str", ) -> Set["int |" " str"]: pass
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/keep_newline_after_match.py
tests/data/cases/keep_newline_after_match.py
# flags: --minimum-version=3.10 def http_status(status): match status: case 400: return "Bad request" case 401: return "Unauthorized" case 403: return "Forbidden" case 404: return "Not found" # output def http_status(status): match status: case 400: return "Bad request" case 401: return "Unauthorized" case 403: return "Forbidden" case 404: return "Not found"
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/module_docstring_3.py
tests/data/cases/module_docstring_3.py
"""Single line module-level docstring should be followed by single newline.""" a = 1 # output """Single line module-level docstring should be followed by single newline.""" a = 1
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/preview_remove_multiline_lone_list_item_parens.py
tests/data/cases/preview_remove_multiline_lone_list_item_parens.py
# flags: --unstable items = [(x for x in [1])] items = [ ( {"key1": "val1", "key2": "val2", "key3": "val3"} if some_var == "long strings" else {"key": "val"} ) ] items = [ ( {"key1": "val1", "key2": "val2"} if some_var == "" else {"key": "val"} ) ] items = [ ( "123456890123457890123468901234567890" if some_var == "long strings" else "123467890123467890" ) ] items = [ ( {"key1": "val1", "key2": "val2", "key3": "val3"} and some_var == "long strings" and {"key": "val"} ) ] items = [ ( "123456890123457890123468901234567890" and some_var == "long strings" and "123467890123467890" ) ] items = [ ( long_variable_name and even_longer_variable_name and yet_another_very_long_variable_name ) ] # Shouldn't remove trailing commas items = [ ( {"key1": "val1", "key2": "val2", "key3": "val3"} if some_var == "long strings" else {"key": "val"} ), ] items = [ ( {"key1": "val1", "key2": "val2", "key3": "val3"} and some_var == "long strings" and {"key": "val"} ), ] items = [ ( "123456890123457890123468901234567890" and some_var == "long strings" and "123467890123467890" ), ] items = [ ( long_variable_name and even_longer_variable_name and yet_another_very_long_variable_name ), ] # Shouldn't add parentheses items = [ {"key1": "val1", "key2": "val2", "key3": "val3"} if some_var == "long strings" else {"key": "val"} ] items = [{"key1": "val1", "key2": "val2"} if some_var == "" else {"key": "val"}] # Shouldn't crash with comments items = [ ( # comment {"key1": "val1", "key2": "val2", "key3": "val3"} if some_var == "long strings" else {"key": "val"} ) ] items = [ ( {"key1": "val1", "key2": "val2", "key3": "val3"} if some_var == "long strings" else {"key": "val"} ) # comment ] items = [ # comment ( {"key1": "val1", "key2": "val2", "key3": "val3"} if some_var == "long strings" else {"key": "val"} ) ] items = [ ( {"key1": "val1", "key2": "val2", "key3": "val3"} if some_var == "long strings" else {"key": "val"} ) ] # comment items = [ ( {"key1": "val1", "key2": "val2", "key3": "val3"} # comment if some_var == "long strings" else {"key": "val"} ) ] items = [ # comment ( # comment {"key1": "val1", "key2": "val2", "key3": "val3"} if some_var == "long strings" else {"key": "val"} ) ] items = [ ( {"key1": "val1", "key2": "val2", "key3": "val3"} if some_var == "long strings" else {"key": "val"} ) # comment ] # comment # output items = [(x for x in [1])] items = [ {"key1": "val1", "key2": "val2", "key3": "val3"} if some_var == "long strings" else {"key": "val"} ] items = [{"key1": "val1", "key2": "val2"} if some_var == "" else {"key": "val"}] items = [ "123456890123457890123468901234567890" if some_var == "long strings" else "123467890123467890" ] items = [ {"key1": "val1", "key2": "val2", "key3": "val3"} and some_var == "long strings" and {"key": "val"} ] items = [ "123456890123457890123468901234567890" and some_var == "long strings" and "123467890123467890" ] items = [ long_variable_name and even_longer_variable_name and yet_another_very_long_variable_name ] # Shouldn't remove trailing commas items = [ ( {"key1": "val1", "key2": "val2", "key3": "val3"} if some_var == "long strings" else {"key": "val"} ), ] items = [ ( {"key1": "val1", "key2": "val2", "key3": "val3"} and some_var == "long strings" and {"key": "val"} ), ] items = [ ( "123456890123457890123468901234567890" and some_var == "long strings" and "123467890123467890" ), ] items = [ ( long_variable_name and even_longer_variable_name and yet_another_very_long_variable_name ), ] # Shouldn't add parentheses items = [ {"key1": "val1", "key2": "val2", "key3": "val3"} if some_var == "long strings" else {"key": "val"} ] items = [{"key1": "val1", "key2": "val2"} if some_var == "" else {"key": "val"}] # Shouldn't crash with comments items = [ # comment {"key1": "val1", "key2": "val2", "key3": "val3"} if some_var == "long strings" else {"key": "val"} ] items = [ {"key1": "val1", "key2": "val2", "key3": "val3"} if some_var == "long strings" else {"key": "val"} ] # comment items = [ # comment {"key1": "val1", "key2": "val2", "key3": "val3"} if some_var == "long strings" else {"key": "val"} ] items = [ {"key1": "val1", "key2": "val2", "key3": "val3"} if some_var == "long strings" else {"key": "val"} ] # comment items = [ {"key1": "val1", "key2": "val2", "key3": "val3"} # comment if some_var == "long strings" else {"key": "val"} ] items = [ # comment # comment {"key1": "val1", "key2": "val2", "key3": "val3"} if some_var == "long strings" else {"key": "val"} ] items = [ {"key1": "val1", "key2": "val2", "key3": "val3"} if some_var == "long strings" else {"key": "val"} ] # comment # comment
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/fmtskip.py
tests/data/cases/fmtskip.py
a, b = 1, 2 c = 6 # fmt: skip d = 5
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/torture.py
tests/data/cases/torture.py
importA;() << 0 ** 101234234242352525425252352352525234890264906820496920680926538059059209922523523525 # assert sort_by_dependency( { "1": {"2", "3"}, "2": {"2a", "2b"}, "3": {"3a", "3b"}, "2a": set(), "2b": set(), "3a": set(), "3b": set() } ) == ["2a", "2b", "2", "3a", "3b", "3", "1"] importA 0;0^0# class A: def foo(self): for _ in range(10): aaaaaaaaaaaaaaaaaaa = bbbbbbbbbbbbbbb.cccccccccc( # pylint: disable=no-member xxxxxxxxxxxx ) def test(self, othr): return (1 == 2 and (name, description, self.default, self.selected, self.auto_generated, self.parameters, self.meta_data, self.schedule) == (name, description, othr.default, othr.selected, othr.auto_generated, othr.parameters, othr.meta_data, othr.schedule)) assert ( a_function(very_long_arguments_that_surpass_the_limit, which_is_eighty_eight_in_this_case_plus_a_bit_more) == {"x": "this need to pass the line limit as well", "b": "but only by a little bit"} ) # output importA ( () << 0 ** 101234234242352525425252352352525234890264906820496920680926538059059209922523523525 ) # assert sort_by_dependency( { "1": {"2", "3"}, "2": {"2a", "2b"}, "3": {"3a", "3b"}, "2a": set(), "2b": set(), "3a": set(), "3b": set(), } ) == ["2a", "2b", "2", "3a", "3b", "3", "1"] importA 0 0 ^ 0 # class A: def foo(self): for _ in range(10): aaaaaaaaaaaaaaaaaaa = bbbbbbbbbbbbbbb.cccccccccc( xxxxxxxxxxxx ) # pylint: disable=no-member def test(self, othr): return 1 == 2 and ( name, description, self.default, self.selected, self.auto_generated, self.parameters, self.meta_data, self.schedule, ) == ( name, description, othr.default, othr.selected, othr.auto_generated, othr.parameters, othr.meta_data, othr.schedule, ) assert a_function( very_long_arguments_that_surpass_the_limit, which_is_eighty_eight_in_this_case_plus_a_bit_more, ) == {"x": "this need to pass the line limit as well", "b": "but only by a little bit"}
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/type_expansion.py
tests/data/cases/type_expansion.py
# flags: --preview --minimum-version=3.12 def f1[T: (int, str)](a,): pass def f2[T: (int, str)](a: int, b,): pass def g1[T: (int,)](a,): pass def g2[T: (int, str, bytes)](a,): pass def g3[T: ((int, str), (bytes,))](a,): pass def g4[T: (int, (str, bytes))](a,): pass def g5[T: ((int,),)](a: int, b,): pass # output def f1[T: (int, str)]( a, ): pass def f2[T: (int, str)]( a: int, b, ): pass def g1[T: (int,)]( a, ): pass def g2[T: (int, str, bytes)]( a, ): pass def g3[T: ((int, str), (bytes,))]( a, ): pass def g4[T: (int, (str, bytes))]( a, ): pass def g5[T: ((int,),)]( a: int, b, ): pass
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/comments2.py
tests/data/cases/comments2.py
from com.my_lovely_company.my_lovely_team.my_lovely_project.my_lovely_component import ( MyLovelyCompanyTeamProjectComponent # NOT DRY ) from com.my_lovely_company.my_lovely_team.my_lovely_project.my_lovely_component import ( MyLovelyCompanyTeamProjectComponent as component # DRY ) # Please keep __all__ alphabetized within each category. __all__ = [ # Super-special typing primitives. 'Any', 'Callable', 'ClassVar', # ABCs (from collections.abc). 'AbstractSet', # collections.abc.Set. 'ByteString', 'Container', # Concrete collection types. 'Counter', 'Deque', 'Dict', 'DefaultDict', 'List', 'Set', 'FrozenSet', 'NamedTuple', # Not really a type. 'Generator', ] not_shareables = [ # singletons True, False, NotImplemented, ..., # builtin types and objects type, object, object(), Exception(), 42, 100.0, "spam", # user-defined types and objects Cheese, Cheese("Wensleydale"), SubBytes(b"spam"), ] if 'PYTHON' in os.environ: add_compiler(compiler_from_env()) else: # for compiler in compilers.values(): # add_compiler(compiler) add_compiler(compilers[(7.0, 32)]) # add_compiler(compilers[(7.1, 64)]) # Comment before function. def inline_comments_in_brackets_ruin_everything(): if typedargslist: parameters.children = [ children[0], # (1 body, children[-1] # )1 ] parameters.children = [ children[0], body, children[-1], # type: ignore ] else: parameters.children = [ parameters.children[0], # (2 what if this was actually long body, parameters.children[-1], # )2 ] parameters.children = [parameters.what_if_this_was_actually_long.children[0], body, parameters.children[-1]] # type: ignore if (self._proc is not None # has the child process finished? and self._returncode is None # the child process has finished, but the # transport hasn't been notified yet? and self._proc.poll() is None): pass # no newline before or after short = [ # one 1, # two 2] # no newline after call(arg1, arg2, """ short """, arg3=True) ############################################################################ call2( #short arg1, #but arg2, #multiline """ short """, # yup arg3=True) lcomp = [ element # yup for element in collection # yup if element is not None # right ] lcomp2 = [ # hello element # yup for element in collection # right if element is not None ] lcomp3 = [ # This one is actually too long to fit in a single line. element.split('\n', 1)[0] # yup for element in collection.select_elements() # right if element is not None ] while True: if False: continue # and round and round we go # and round and round we go # let's return return Node( syms.simple_stmt, [ Node(statement, result), Leaf(token.NEWLINE, '\n') # FIXME: \r\n? ], ) CONFIG_FILES = [CONFIG_FILE, ] + SHARED_CONFIG_FILES + USER_CONFIG_FILES # type: Final class Test: def _init_host(self, parsed) -> None: if (parsed.hostname is None or # type: ignore not parsed.hostname.strip()): pass ####################### ### SECTION COMMENT ### ####################### instruction()#comment with bad spacing # END COMMENTS # MORE END COMMENTS # output from com.my_lovely_company.my_lovely_team.my_lovely_project.my_lovely_component import ( MyLovelyCompanyTeamProjectComponent, # NOT DRY ) from com.my_lovely_company.my_lovely_team.my_lovely_project.my_lovely_component import ( MyLovelyCompanyTeamProjectComponent as component, # DRY ) # Please keep __all__ alphabetized within each category. __all__ = [ # Super-special typing primitives. "Any", "Callable", "ClassVar", # ABCs (from collections.abc). "AbstractSet", # collections.abc.Set. "ByteString", "Container", # Concrete collection types. "Counter", "Deque", "Dict", "DefaultDict", "List", "Set", "FrozenSet", "NamedTuple", # Not really a type. "Generator", ] not_shareables = [ # singletons True, False, NotImplemented, ..., # builtin types and objects type, object, object(), Exception(), 42, 100.0, "spam", # user-defined types and objects Cheese, Cheese("Wensleydale"), SubBytes(b"spam"), ] if "PYTHON" in os.environ: add_compiler(compiler_from_env()) else: # for compiler in compilers.values(): # add_compiler(compiler) add_compiler(compilers[(7.0, 32)]) # add_compiler(compilers[(7.1, 64)]) # Comment before function. def inline_comments_in_brackets_ruin_everything(): if typedargslist: parameters.children = [children[0], body, children[-1]] # (1 # )1 parameters.children = [ children[0], body, children[-1], # type: ignore ] else: parameters.children = [ parameters.children[0], # (2 what if this was actually long body, parameters.children[-1], # )2 ] parameters.children = [parameters.what_if_this_was_actually_long.children[0], body, parameters.children[-1]] # type: ignore if ( self._proc is not None # has the child process finished? and self._returncode is None # the child process has finished, but the # transport hasn't been notified yet? and self._proc.poll() is None ): pass # no newline before or after short = [ # one 1, # two 2, ] # no newline after call( arg1, arg2, """ short """, arg3=True, ) ############################################################################ call2( # short arg1, # but arg2, # multiline """ short """, # yup arg3=True, ) lcomp = [ element for element in collection if element is not None # yup # yup # right ] lcomp2 = [ # hello element # yup for element in collection # right if element is not None ] lcomp3 = [ # This one is actually too long to fit in a single line. element.split("\n", 1)[0] # yup for element in collection.select_elements() # right if element is not None ] while True: if False: continue # and round and round we go # and round and round we go # let's return return Node( syms.simple_stmt, [Node(statement, result), Leaf(token.NEWLINE, "\n")], # FIXME: \r\n? ) CONFIG_FILES = ( [ CONFIG_FILE, ] + SHARED_CONFIG_FILES + USER_CONFIG_FILES ) # type: Final class Test: def _init_host(self, parsed) -> None: if parsed.hostname is None or not parsed.hostname.strip(): # type: ignore pass ####################### ### SECTION COMMENT ### ####################### instruction() # comment with bad spacing # END COMMENTS # MORE END COMMENTS
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/docstring.py
tests/data/cases/docstring.py
class MyClass: """ Multiline class docstring """ def method(self): """Multiline method docstring """ pass def foo(): """This is a docstring with some lines of text here """ return def bar(): '''This is another docstring with more lines of text ''' return def baz(): '''"This" is a string with some embedded "quotes"''' return def troz(): '''Indentation with tabs is just as OK ''' return def zort(): """Another multiline docstring """ pass def poit(): """ Lorem ipsum dolor sit amet. Consectetur adipiscing elit: - sed do eiusmod tempor incididunt ut labore - dolore magna aliqua - enim ad minim veniam - quis nostrud exercitation ullamco laboris nisi - aliquip ex ea commodo consequat """ pass def under_indent(): """ These lines are indented in a way that does not make sense. """ pass def over_indent(): """ This has a shallow indent - But some lines are deeper - And the closing quote is too deep """ pass def single_line(): """But with a newline after it! """ pass def this(): r""" 'hey ho' """ def that(): """ "hey yah" """ def and_that(): """ "hey yah" """ def and_this(): ''' "hey yah"''' def multiline_whitespace(): ''' ''' def oneline_whitespace(): ''' ''' def empty(): """""" def single_quotes(): 'testing' def believe_it_or_not_this_is_in_the_py_stdlib(): ''' "hey yah"''' def ignored_docstring(): """a => \ b""" def single_line_docstring_with_whitespace(): """ This should be stripped """ def docstring_with_inline_tabs_and_space_indentation(): """hey tab separated value tab at start of line and then a tab separated value multiple tabs at the beginning and inline mixed tabs and spaces at beginning. next line has mixed tabs and spaces only. line ends with some tabs """ def docstring_with_inline_tabs_and_tab_indentation(): """hey tab separated value tab at start of line and then a tab separated value multiple tabs at the beginning and inline mixed tabs and spaces at beginning. next line has mixed tabs and spaces only. line ends with some tabs """ pass def backslash_space(): """\ """ def multiline_backslash_1(): ''' hey\there\ \ ''' def multiline_backslash_2(): ''' hey there \ ''' # Regression test for #3425 def multiline_backslash_really_long_dont_crash(): """ hey there hello guten tag hi hoow are you ola zdravstvuyte ciao como estas ca va \ """ def multiline_backslash_3(): ''' already escaped \\ ''' def my_god_its_full_of_stars_1(): "I'm sorry Dave\u2001" # the space below is actually a \u2001, removed in output def my_god_its_full_of_stars_2(): "I'm sorry Dave " def docstring_almost_at_line_limit(): """long docstring.................................................................""" def docstring_almost_at_line_limit2(): """long docstring................................................................. .................................................................................. """ def docstring_at_line_limit(): """long docstring................................................................""" def multiline_docstring_at_line_limit(): """first line----------------------------------------------------------------------- second line----------------------------------------------------------------------""" def stable_quote_normalization_with_immediate_inner_single_quote(self): ''''<text here> <text here, since without another non-empty line black is stable> ''' def foo(): """ Docstring with a backslash followed by a space\ and then another line """ # output class MyClass: """Multiline class docstring """ def method(self): """Multiline method docstring """ pass def foo(): """This is a docstring with some lines of text here """ return def bar(): """This is another docstring with more lines of text """ return def baz(): '''"This" is a string with some embedded "quotes"''' return def troz(): """Indentation with tabs is just as OK """ return def zort(): """Another multiline docstring """ pass def poit(): """ Lorem ipsum dolor sit amet. Consectetur adipiscing elit: - sed do eiusmod tempor incididunt ut labore - dolore magna aliqua - enim ad minim veniam - quis nostrud exercitation ullamco laboris nisi - aliquip ex ea commodo consequat """ pass def under_indent(): """ These lines are indented in a way that does not make sense. """ pass def over_indent(): """ This has a shallow indent - But some lines are deeper - And the closing quote is too deep """ pass def single_line(): """But with a newline after it!""" pass def this(): r""" 'hey ho' """ def that(): """ "hey yah" """ def and_that(): """ "hey yah" """ def and_this(): ''' "hey yah"''' def multiline_whitespace(): """ """ def oneline_whitespace(): """ """ def empty(): """""" def single_quotes(): "testing" def believe_it_or_not_this_is_in_the_py_stdlib(): ''' "hey yah"''' def ignored_docstring(): """a => \ b""" def single_line_docstring_with_whitespace(): """This should be stripped""" def docstring_with_inline_tabs_and_space_indentation(): """hey tab separated value tab at start of line and then a tab separated value multiple tabs at the beginning and inline mixed tabs and spaces at beginning. next line has mixed tabs and spaces only. line ends with some tabs """ def docstring_with_inline_tabs_and_tab_indentation(): """hey tab separated value tab at start of line and then a tab separated value multiple tabs at the beginning and inline mixed tabs and spaces at beginning. next line has mixed tabs and spaces only. line ends with some tabs """ pass def backslash_space(): """\ """ def multiline_backslash_1(): """ hey\there\ \ """ def multiline_backslash_2(): """ hey there \ """ # Regression test for #3425 def multiline_backslash_really_long_dont_crash(): """ hey there hello guten tag hi hoow are you ola zdravstvuyte ciao como estas ca va \ """ def multiline_backslash_3(): """ already escaped \\""" def my_god_its_full_of_stars_1(): "I'm sorry Dave\u2001" # the space below is actually a \u2001, removed in output def my_god_its_full_of_stars_2(): "I'm sorry Dave" def docstring_almost_at_line_limit(): """long docstring.................................................................""" def docstring_almost_at_line_limit2(): """long docstring................................................................. .................................................................................. """ def docstring_at_line_limit(): """long docstring................................................................""" def multiline_docstring_at_line_limit(): """first line----------------------------------------------------------------------- second line----------------------------------------------------------------------""" def stable_quote_normalization_with_immediate_inner_single_quote(self): """'<text here> <text here, since without another non-empty line black is stable> """ def foo(): """ Docstring with a backslash followed by a space\ and then another line """
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/module_docstring_followed_by_function.py
tests/data/cases/module_docstring_followed_by_function.py
"""Two blank lines between module docstring and a function def.""" def function(): pass # output """Two blank lines between module docstring and a function def.""" def function(): pass
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/remove_with_brackets.py
tests/data/cases/remove_with_brackets.py
with (open("bla.txt")): pass with (open("bla.txt")), (open("bla.txt")): pass with (open("bla.txt") as f): pass # Remove brackets within alias expression with (open("bla.txt")) as f: pass # Remove brackets around one-line context managers with (open("bla.txt") as f, (open("x"))): pass with ((open("bla.txt")) as f, open("x")): pass with (CtxManager1() as example1, CtxManager2() as example2): ... # Brackets remain when using magic comma with (CtxManager1() as example1, CtxManager2() as example2,): ... # Brackets remain for multi-line context managers with (CtxManager1() as example1, CtxManager2() as example2, CtxManager2() as example2, CtxManager2() as example2, CtxManager2() as example2): ... # Don't touch assignment expressions with (y := open("./test.py")) as f: pass # Deeply nested examples # N.B. Multiple brackets are only possible # around the context manager itself. # Only one brackets is allowed around the # alias expression or comma-delimited context managers. with (((open("bla.txt")))): pass with (((open("bla.txt")))), (((open("bla.txt")))): pass with (((open("bla.txt")))) as f: pass with ((((open("bla.txt")))) as f): pass with ((((CtxManager1()))) as example1, (((CtxManager2()))) as example2): ... # regression tests for #3678 with (a, *b): pass with (a, (b, *c)): pass with (a for b in c): pass with (a, (b for c in d)): pass # output with open("bla.txt"): pass with open("bla.txt"), open("bla.txt"): pass with open("bla.txt") as f: pass # Remove brackets within alias expression with open("bla.txt") as f: pass # Remove brackets around one-line context managers with open("bla.txt") as f, open("x"): pass with open("bla.txt") as f, open("x"): pass with CtxManager1() as example1, CtxManager2() as example2: ... # Brackets remain when using magic comma with ( CtxManager1() as example1, CtxManager2() as example2, ): ... # Brackets remain for multi-line context managers with ( CtxManager1() as example1, CtxManager2() as example2, CtxManager2() as example2, CtxManager2() as example2, CtxManager2() as example2, ): ... # Don't touch assignment expressions with (y := open("./test.py")) as f: pass # Deeply nested examples # N.B. Multiple brackets are only possible # around the context manager itself. # Only one brackets is allowed around the # alias expression or comma-delimited context managers. with open("bla.txt"): pass with open("bla.txt"), open("bla.txt"): pass with open("bla.txt") as f: pass with open("bla.txt") as f: pass with CtxManager1() as example1, CtxManager2() as example2: ... # regression tests for #3678 with (a, *b): pass with a, (b, *c): pass with (a for b in c): pass with a, (b for c in d): pass
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/numeric_literals.py
tests/data/cases/numeric_literals.py
x = 123456789 x = 123456 x = .1 x = 1. x = 1E+1 x = 1E-1 x = 1.000_000_01 x = 123456789.123456789 x = 123456789.123456789E123456789 x = 123456789E123456789 x = 123456789J x = 123456789.123456789J x = 0XB1ACC x = 0B1011 x = 0O777 x = 0.000000006 x = 10000 x = 133333 # output x = 123456789 x = 123456 x = 0.1 x = 1.0 x = 1e1 x = 1e-1 x = 1.000_000_01 x = 123456789.123456789 x = 123456789.123456789e123456789 x = 123456789e123456789 x = 123456789j x = 123456789.123456789j x = 0xB1ACC x = 0b1011 x = 0o777 x = 0.000000006 x = 10000 x = 133333
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/remove_redundant_parens_in_case_guard.py
tests/data/cases/remove_redundant_parens_in_case_guard.py
# flags: --minimum-version=3.10 --line-length=79 match 1: case _ if (True): pass match 1: case _ if ( True ): pass match 1: case _ if ( # this is a comment True ): pass match 1: case _ if ( True # this is a comment ): pass match 1: case _ if ( True # this is a comment ): pass match 1: case _ if ( # this is a comment True ): pass match 1: case _ if ( True ): # this is a comment pass match 1: case _ if (True): # comment over the line limit unless parens are removed x pass match 1: case _ if (True): # comment over the line limit and parens should go to next line pass # output match 1: case _ if True: pass match 1: case _ if True: pass match 1: case _ if ( # this is a comment True ): pass match 1: case _ if ( True # this is a comment ): pass match 1: case _ if True: # this is a comment pass match 1: case _ if True: # this is a comment pass match 1: case _ if True: # this is a comment pass match 1: case _ if True: # comment over the line limit unless parens are removed x pass match 1: case ( _ ) if True: # comment over the line limit and parens should go to next line pass
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/long_strings_flag_disabled.py
tests/data/cases/long_strings_flag_disabled.py
x = "This is a really long string that can't possibly be expected to fit all together on one line. In fact it may even take up three or more lines... like four or five... but probably just three." x += "This is a really long string that can't possibly be expected to fit all together on one line. In fact it may even take up three or more lines... like four or five... but probably just three." y = "Short string" print( "This is a really long string inside of a print statement with extra arguments attached at the end of it.", x, y, z, ) print( "This is a really long string inside of a print statement with no extra arguments attached at the end of it." ) D1 = { "The First": "This is a really long string that can't possibly be expected to fit all together on one line. Also it is inside a dictionary, so formatting is more difficult.", "The Second": "This is another really really (not really) long string that also can't be expected to fit on one line and is, like the other string, inside a dictionary.", } D2 = { 1.0: "This is a really long string that can't possibly be expected to fit all together on one line. Also it is inside a dictionary, so formatting is more difficult.", 2.0: "This is another really really (not really) long string that also can't be expected to fit on one line and is, like the other string, inside a dictionary.", } D3 = { x: "This is a really long string that can't possibly be expected to fit all together on one line. Also it is inside a dictionary, so formatting is more difficult.", y: "This is another really really (not really) long string that also can't be expected to fit on one line and is, like the other string, inside a dictionary.", } D4 = { "A long and ridiculous {}".format( string_key ): "This is a really really really long string that has to go i,side of a dictionary. It is soooo bad.", some_func( "calling", "some", "stuff" ): "This is a really really really long string that has to go inside of a dictionary. It is {soooo} bad (#{x}).".format( sooo="soooo", x=2 ), "A %s %s" % ( "formatted", "string", ): ( "This is a really really really long string that has to go inside of a dictionary. It is %s bad (#%d)." % ("soooo", 2) ), } func_with_keywords( my_arg, my_kwarg="Long keyword strings also need to be wrapped, but they will probably need to be handled a little bit differently.", ) bad_split1 = ( "But what should happen when code has already been formatted but in the wrong way? Like" " with a space at the end instead of the beginning. Or what about when it is split too soon?" ) bad_split2 = ( "But what should happen when code has already " "been formatted but in the wrong way? Like " "with a space at the end instead of the " "beginning. Or what about when it is split too " "soon? In the case of a split that is too " "short, black will try to honer the custom " "split." ) bad_split3 = ( "What if we have inline comments on " # First Comment "each line of a bad split? In that " # Second Comment "case, we should just leave it alone." # Third Comment ) bad_split_func1( "But what should happen when code has already " "been formatted but in the wrong way? Like " "with a space at the end instead of the " "beginning. Or what about when it is split too " "soon? In the case of a split that is too " "short, black will try to honer the custom " "split.", xxx, yyy, zzz, ) bad_split_func2( xxx, yyy, zzz, long_string_kwarg="But what should happen when code has already been formatted but in the wrong way? Like " "with a space at the end instead of the beginning. Or what about when it is split too " "soon?", ) bad_split_func3( ( "But what should happen when code has already " r"been formatted but in the wrong way? Like " "with a space at the end instead of the " r"beginning. Or what about when it is split too " r"soon? In the case of a split that is too " "short, black will try to honer the custom " "split." ), xxx, yyy, zzz, ) raw_string = r"This is a long raw string. When re-formatting this string, black needs to make sure it prepends the 'r' onto the new string." fmt_string1 = "We also need to be sure to preserve any and all {} which may or may not be attached to the string in question.".format( "method calls" ) fmt_string2 = "But what about when the string is {} but {}".format( "short", "the method call is really really really really really really really really long?", ) old_fmt_string1 = ( "While we are on the topic of %s, we should also note that old-style formatting must also be preserved, since some %s still uses it." % ("formatting", "code") ) old_fmt_string2 = "This is a %s %s %s %s" % ( "really really really really really", "old", "way to format strings!", "Use f-strings instead!", ) old_fmt_string3 = ( "Whereas only the strings after the percent sign were long in the last example, this example uses a long initial string as well. This is another %s %s %s %s" % ( "really really really really really", "old", "way to format strings!", "Use f-strings instead!", ) ) fstring = f"f-strings definitely make things more {difficult} than they need to be for {{black}}. But boy they sure are handy. The problem is that some lines will need to have the 'f' whereas others do not. This {line}, for example, needs one." fstring_with_no_fexprs = f"Some regular string that needs to get split certainly but is NOT an fstring by any means whatsoever." comment_string = "Long lines with inline comments should have their comments appended to the reformatted string's enclosing right parentheses." # This comment gets thrown to the top. arg_comment_string = print( "Long lines with inline comments which are apart of (and not the only member of) an argument list should have their comments appended to the reformatted string's enclosing left parentheses.", # This comment stays on the bottom. "Arg #2", "Arg #3", "Arg #4", "Arg #5", ) pragma_comment_string1 = "Lines which end with an inline pragma comment of the form `# <pragma>: <...>` should be left alone." # noqa: E501 pragma_comment_string2 = "Lines which end with an inline pragma comment of the form `# <pragma>: <...>` should be left alone." # noqa """This is a really really really long triple quote string and it should not be touched.""" triple_quote_string = """This is a really really really long triple quote string assignment and it should not be touched.""" assert ( some_type_of_boolean_expression ), "Followed by a really really really long string that is used to provide context to the AssertionError exception." assert ( some_type_of_boolean_expression ), "Followed by a really really really long string that is used to provide context to the AssertionError exception, which uses dynamic string {}.".format( "formatting" ) assert some_type_of_boolean_expression, ( "Followed by a really really really long string that is used to provide context to the AssertionError exception, which uses dynamic string %s." % "formatting" ) assert some_type_of_boolean_expression, ( "Followed by a really really really long string that is used to provide context to the AssertionError exception, which uses dynamic %s %s." % ("string", "formatting") ) some_function_call( "With a reallly generic name and with a really really long string that is, at some point down the line, " + added + " to a variable and then added to another string." ) some_function_call( "With a reallly generic name and with a really really long string that is, at some point down the line, " + added + " to a variable and then added to another string. But then what happens when the final string is also supppppperrrrr long?! Well then that second (realllllllly long) string should be split too.", "and a second argument", and_a_third, ) return "A really really really really really really really really really really really really really long {} {}".format( "return", "value" ) func_with_bad_comma( "This is a really long string argument to a function that has a trailing comma which should NOT be there.", ) func_with_bad_comma( "This is a really long string argument to a function that has a trailing comma which should NOT be there.", # comment after comma ) func_with_bad_comma( ( "This is a really long string argument to a function that has a trailing comma" " which should NOT be there." ), ) func_with_bad_comma( ( "This is a really long string argument to a function that has a trailing comma" " which should NOT be there." ), # comment after comma ) func_with_bad_parens_that_wont_fit_in_one_line( ("short string that should have parens stripped"), x, y, z ) func_with_bad_parens_that_wont_fit_in_one_line( x, y, ("short string that should have parens stripped"), z ) func_with_bad_parens( ("short string that should have parens stripped"), x, y, z, ) func_with_bad_parens( x, y, ("short string that should have parens stripped"), z, ) annotated_variable: Final = ( "This is a large " + STRING + " that has been " + CONCATENATED + "using the '+' operator." ) annotated_variable: Final = ( "This is a large string that has a type annotation attached to it. A type annotation should NOT stop a long string from being wrapped." ) annotated_variable: Literal["fakse_literal"] = ( "This is a large string that has a type annotation attached to it. A type annotation should NOT stop a long string from being wrapped." ) backslashes = "This is a really long string with \"embedded\" double quotes and 'single' quotes that also handles checking for an even number of backslashes \\" backslashes = "This is a really long string with \"embedded\" double quotes and 'single' quotes that also handles checking for an even number of backslashes \\\\" backslashes = "This is a really 'long' string with \"embedded double quotes\" and 'single' quotes that also handles checking for an odd number of backslashes \\\", like this...\\\\\\" short_string = "Hi" " there." func_call(short_string=("Hi" " there.")) raw_strings = r"Don't" " get" r" merged" " unless they are all raw." def foo(): yield "This is a really long string that can't possibly be expected to fit all together on one line. In fact it may even take up three or more lines... like four or five... but probably just three." x = f"This is a {{really}} long string that needs to be split without a doubt (i.e. most definitely). In short, this {string} that can't possibly be {{expected}} to fit all together on one line. In {fact} it may even take up three or more lines... like four or five... but probably just four." long_unmergable_string_with_pragma = ( "This is a really long string that can't be merged because it has a likely pragma at the end" # type: ignore " of it." ) long_unmergable_string_with_pragma = ( "This is a really long string that can't be merged because it has a likely pragma at the end" # noqa " of it." ) long_unmergable_string_with_pragma = ( "This is a really long string that can't be merged because it has a likely pragma at the end" # pylint: disable=some-pylint-check " of it." )
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/trailing_comma_optional_parens3.py
tests/data/cases/trailing_comma_optional_parens3.py
if True: if True: if True: return _( "qweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweas " + "qweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqwegqweasdzxcqweasdzxc.", "qweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqwe", ) % {"reported_username": reported_username, "report_reason": report_reason} # output if True: if True: if True: return _( "qweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweas " + "qweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqwegqweasdzxcqweasdzxc.", "qweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqwe", ) % {"reported_username": reported_username, "report_reason": report_reason}
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/prefer_rhs_split_reformatted.py
tests/data/cases/prefer_rhs_split_reformatted.py
# Test cases separate from `prefer_rhs_split.py` that contains unformatted source. # Left hand side fits in a single line but will still be exploded by the # magic trailing comma. first_value, (m1, m2,), third_value = xxxxxx_yyyyyy_zzzzzz_wwwwww_uuuuuuu_vvvvvvvvvvv( arg1, arg2, ) # Make when when the left side of assignment plus the opening paren "... = (" is # exactly line length limit + 1, it won't be split like that. xxxxxxxxx_yyy_zzzzzzzz[xx.xxxxxx(x_yyy_zzzzzz.xxxxx[0]), x_yyy_zzzzzz.xxxxxx(xxxx=1)] = 1 # Regression test for #1187 print( dict( a=1, b=2 if some_kind_of_data is not None else some_other_kind_of_data, # some explanation of why this is actually necessary c=3, ) ) # output # Test cases separate from `prefer_rhs_split.py` that contains unformatted source. # Left hand side fits in a single line but will still be exploded by the # magic trailing comma. ( first_value, ( m1, m2, ), third_value, ) = xxxxxx_yyyyyy_zzzzzz_wwwwww_uuuuuuu_vvvvvvvvvvv( arg1, arg2, ) # Make when when the left side of assignment plus the opening paren "... = (" is # exactly line length limit + 1, it won't be split like that. xxxxxxxxx_yyy_zzzzzzzz[ xx.xxxxxx(x_yyy_zzzzzz.xxxxx[0]), x_yyy_zzzzzz.xxxxxx(xxxx=1) ] = 1 # Regression test for #1187 print( dict( a=1, b=( 2 if some_kind_of_data is not None else some_other_kind_of_data ), # some explanation of why this is actually necessary c=3, ) )
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/async_stmts.py
tests/data/cases/async_stmts.py
async def func() -> (int): return 0 @decorated async def func() -> (int): return 0 async for (item) in async_iter: pass # output async def func() -> int: return 0 @decorated async def func() -> int: return 0 async for item in async_iter: pass
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/collections.py
tests/data/cases/collections.py
import core, time, a from . import A, B, C # keeps existing trailing comma from foo import ( bar, ) # also keeps existing structure from foo import ( baz, qux, ) # `as` works as well from foo import ( xyzzy as magic, ) a = {1,2,3,} b = { 1,2, 3} c = { 1, 2, 3, } x = 1, y = narf(), nested = {(1,2,3),(4,5,6),} nested_no_trailing_comma = {(1,2,3),(4,5,6)} nested_long_lines = ["aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", "cccccccccccccccccccccccccccccccccccccccc", (1, 2, 3), "dddddddddddddddddddddddddddddddddddddddd"] {"oneple": (1,),} {"oneple": (1,)} ['ls', 'lsoneple/%s' % (foo,)] x = {"oneple": (1,)} y = {"oneple": (1,),} assert False, ("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa wraps %s" % bar) # looping over a 1-tuple should also not get wrapped for x in (1,): pass for (x,) in (1,), (2,), (3,): pass [1, 2, 3,] division_result_tuple = (6/2,) print("foo %r", (foo.bar,)) if True: IGNORED_TYPES_FOR_ATTRIBUTE_CHECKING = ( Config.IGNORED_TYPES_FOR_ATTRIBUTE_CHECKING | {pylons.controllers.WSGIController} ) if True: ec2client.get_waiter('instance_stopped').wait( InstanceIds=[instance.id], WaiterConfig={ 'Delay': 5, }) ec2client.get_waiter("instance_stopped").wait( InstanceIds=[instance.id], WaiterConfig={"Delay": 5,}, ) ec2client.get_waiter("instance_stopped").wait( InstanceIds=[instance.id], WaiterConfig={"Delay": 5,}, ) # output import core, time, a from . import A, B, C # keeps existing trailing comma from foo import ( bar, ) # also keeps existing structure from foo import ( baz, qux, ) # `as` works as well from foo import ( xyzzy as magic, ) a = { 1, 2, 3, } b = {1, 2, 3} c = { 1, 2, 3, } x = (1,) y = (narf(),) nested = { (1, 2, 3), (4, 5, 6), } nested_no_trailing_comma = {(1, 2, 3), (4, 5, 6)} nested_long_lines = [ "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", "cccccccccccccccccccccccccccccccccccccccc", (1, 2, 3), "dddddddddddddddddddddddddddddddddddddddd", ] { "oneple": (1,), } {"oneple": (1,)} ["ls", "lsoneple/%s" % (foo,)] x = {"oneple": (1,)} y = { "oneple": (1,), } assert False, ( "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa wraps %s" % bar ) # looping over a 1-tuple should also not get wrapped for x in (1,): pass for (x,) in (1,), (2,), (3,): pass [ 1, 2, 3, ] division_result_tuple = (6 / 2,) print("foo %r", (foo.bar,)) if True: IGNORED_TYPES_FOR_ATTRIBUTE_CHECKING = ( Config.IGNORED_TYPES_FOR_ATTRIBUTE_CHECKING | {pylons.controllers.WSGIController} ) if True: ec2client.get_waiter("instance_stopped").wait( InstanceIds=[instance.id], WaiterConfig={ "Delay": 5, }, ) ec2client.get_waiter("instance_stopped").wait( InstanceIds=[instance.id], WaiterConfig={ "Delay": 5, }, ) ec2client.get_waiter("instance_stopped").wait( InstanceIds=[instance.id], WaiterConfig={ "Delay": 5, }, )
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/comments_non_breaking_space.py
tests/data/cases/comments_non_breaking_space.py
from .config import ( ConfigTypeAttributes, Int, Path, # String, # DEFAULT_TYPE_ATTRIBUTES, ) result = 1 # A simple comment result = ( 1, ) # Another one result = 1 # type: ignore result = 1# This comment is talking about type: ignore square = Square(4) # type: Optional[Square] def function(a:int=42): """ This docstring is already formatted a b """ #  There's a NBSP + 3 spaces before # And 4 spaces on the next line pass # output from .config import ( ConfigTypeAttributes, Int, Path, # String, # DEFAULT_TYPE_ATTRIBUTES, ) result = 1 # A simple comment result = (1,) # Another one result = 1 #  type: ignore result = 1 # This comment is talking about type: ignore square = Square(4) #  type: Optional[Square] def function(a: int = 42): """This docstring is already formatted a b """ # There's a NBSP + 3 spaces before # And 4 spaces on the next line pass
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/function.py
tests/data/cases/function.py
#!/usr/bin/env python3 import asyncio import sys from third_party import X, Y, Z from library import some_connection, \ some_decorator f'trigger 3.6 mode' def func_no_args(): a; b; c if True: raise RuntimeError if False: ... for i in range(10): print(i) continue exec("new-style exec", {}, {}) return None async def coroutine(arg, exec=False): "Single-line docstring. Multiline is harder to reformat." async with some_connection() as conn: await conn.do_what_i_mean('SELECT bobby, tables FROM xkcd', timeout=2) await asyncio.sleep(1) @asyncio.coroutine @some_decorator( with_args=True, many_args=[1,2,3] ) def function_signature_stress_test(number:int,no_annotation=None,text:str="default",* ,debug:bool=False,**kwargs) -> str: return text[number:-1] def spaces(a=1, b=(), c=[], d={}, e=True, f=-1, g=1 if False else 2, h="", i=r''): offset = attr.ib(default=attr.Factory( lambda: _r.uniform(10000, 200000))) assert task._cancel_stack[:len(old_stack)] == old_stack def spaces_types(a: int = 1, b: tuple = (), c: list = [], d: dict = {}, e: bool = True, f: int = -1, g: int = 1 if False else 2, h: str = "", i: str = r''): ... def spaces2(result= _core.Value(None)): assert fut is self._read_fut, (fut, self._read_fut) # EMPTY LINE WITH WHITESPACE (this comment will be removed) def example(session): result = session.query(models.Customer.id).filter( models.Customer.account_id == account_id, models.Customer.email == email_address, ).order_by( models.Customer.id.asc() ).all() def long_lines(): if True: typedargslist.extend( gen_annotated_params(ast_args.kwonlyargs, ast_args.kw_defaults, parameters, implicit_default=True) ) typedargslist.extend( gen_annotated_params( ast_args.kwonlyargs, ast_args.kw_defaults, parameters, implicit_default=True, # trailing standalone comment ) ) _type_comment_re = re.compile( r""" ^ [\t ]* \#[ ]type:[ ]* (?P<type> [^#\t\n]+? ) (?<!ignore) # note: this will force the non-greedy + in <type> to match # a trailing space which is why we need the silliness below (?<!ignore[ ]{1})(?<!ignore[ ]{2})(?<!ignore[ ]{3})(?<!ignore[ ]{4}) (?<!ignore[ ]{5})(?<!ignore[ ]{6})(?<!ignore[ ]{7})(?<!ignore[ ]{8}) (?<!ignore[ ]{9})(?<!ignore[ ]{10}) [\t ]* (?P<nl> (?:\#[^\n]*)? \n? ) $ """, re.MULTILINE | re.VERBOSE ) def trailing_comma(): mapping = { A: 0.25 * (10.0 / 12), B: 0.1 * (10.0 / 12), C: 0.1 * (10.0 / 12), D: 0.1 * (10.0 / 12), } def f( a, **kwargs, ) -> A: return ( yield from A( very_long_argument_name1=very_long_value_for_the_argument, very_long_argument_name2=very_long_value_for_the_argument, **kwargs, ) ) def __await__(): return (yield) # output #!/usr/bin/env python3 import asyncio import sys from third_party import X, Y, Z from library import some_connection, some_decorator f"trigger 3.6 mode" def func_no_args(): a b c if True: raise RuntimeError if False: ... for i in range(10): print(i) continue exec("new-style exec", {}, {}) return None async def coroutine(arg, exec=False): "Single-line docstring. Multiline is harder to reformat." async with some_connection() as conn: await conn.do_what_i_mean("SELECT bobby, tables FROM xkcd", timeout=2) await asyncio.sleep(1) @asyncio.coroutine @some_decorator(with_args=True, many_args=[1, 2, 3]) def function_signature_stress_test( number: int, no_annotation=None, text: str = "default", *, debug: bool = False, **kwargs, ) -> str: return text[number:-1] def spaces(a=1, b=(), c=[], d={}, e=True, f=-1, g=1 if False else 2, h="", i=r""): offset = attr.ib(default=attr.Factory(lambda: _r.uniform(10000, 200000))) assert task._cancel_stack[: len(old_stack)] == old_stack def spaces_types( a: int = 1, b: tuple = (), c: list = [], d: dict = {}, e: bool = True, f: int = -1, g: int = 1 if False else 2, h: str = "", i: str = r"", ): ... def spaces2(result=_core.Value(None)): assert fut is self._read_fut, (fut, self._read_fut) def example(session): result = ( session.query(models.Customer.id) .filter( models.Customer.account_id == account_id, models.Customer.email == email_address, ) .order_by(models.Customer.id.asc()) .all() ) def long_lines(): if True: typedargslist.extend( gen_annotated_params( ast_args.kwonlyargs, ast_args.kw_defaults, parameters, implicit_default=True, ) ) typedargslist.extend( gen_annotated_params( ast_args.kwonlyargs, ast_args.kw_defaults, parameters, implicit_default=True, # trailing standalone comment ) ) _type_comment_re = re.compile( r""" ^ [\t ]* \#[ ]type:[ ]* (?P<type> [^#\t\n]+? ) (?<!ignore) # note: this will force the non-greedy + in <type> to match # a trailing space which is why we need the silliness below (?<!ignore[ ]{1})(?<!ignore[ ]{2})(?<!ignore[ ]{3})(?<!ignore[ ]{4}) (?<!ignore[ ]{5})(?<!ignore[ ]{6})(?<!ignore[ ]{7})(?<!ignore[ ]{8}) (?<!ignore[ ]{9})(?<!ignore[ ]{10}) [\t ]* (?P<nl> (?:\#[^\n]*)? \n? ) $ """, re.MULTILINE | re.VERBOSE, ) def trailing_comma(): mapping = { A: 0.25 * (10.0 / 12), B: 0.1 * (10.0 / 12), C: 0.1 * (10.0 / 12), D: 0.1 * (10.0 / 12), } def f( a, **kwargs, ) -> A: return ( yield from A( very_long_argument_name1=very_long_value_for_the_argument, very_long_argument_name2=very_long_value_for_the_argument, **kwargs, ) ) def __await__(): return (yield)
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/function_trailing_comma.py
tests/data/cases/function_trailing_comma.py
def f(a,): d = {'key': 'value',} tup = (1,) def f2(a,b,): d = {'key': 'value', 'key2': 'value2',} tup = (1,2,) def f(a:int=1,): call(arg={'explode': 'this',}) call2(arg=[1,2,3],) x = { "a": 1, "b": 2, }["a"] if a == {"a": 1,"b": 2,"c": 3,"d": 4,"e": 5,"f": 6,"g": 7,"h": 8,}["a"]: pass def xxxxxxxxxxxxxxxxxxxxxxxxxxxx() -> Set[ "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" ]: json = {"k": {"k2": {"k3": [1,]}}} # The type annotation shouldn't get a trailing comma since that would change its type. # Relevant bug report: https://github.com/psf/black/issues/2381. def some_function_with_a_really_long_name() -> ( returning_a_deeply_nested_import_of_a_type_i_suppose ): pass def some_method_with_a_really_long_name(very_long_parameter_so_yeah: str, another_long_parameter: int) -> ( another_case_of_returning_a_deeply_nested_import_of_a_type_i_suppose_cause_why_not ): pass def func() -> ( also_super_long_type_annotation_that_may_cause_an_AST_related_crash_in_black(this_shouldn_t_get_a_trailing_comma_too) ): pass def func() -> ((also_super_long_type_annotation_that_may_cause_an_AST_related_crash_in_black( this_shouldn_t_get_a_trailing_comma_too )) ): pass # Make sure inner one-element tuple won't explode some_module.some_function( argument1, (one_element_tuple,), argument4, argument5, argument6 ) # Inner trailing comma causes outer to explode some_module.some_function( argument1, (one, two,), argument4, argument5, argument6 ) def foo() -> ( # comment inside parenthesised return type int ): ... def foo() -> ( # comment inside parenthesised return type # more int # another ): ... def foo() -> ( # comment inside parenthesised new union return type int | str | bytes ): ... def foo() -> ( # comment inside plain tuple ): pass def foo(arg: (# comment with non-return annotation int # comment with non-return annotation )): pass def foo(arg: (# comment with non-return annotation int | range | memoryview # comment with non-return annotation )): pass def foo(arg: (# only before int )): pass def foo(arg: ( int # only after )): pass variable: ( # annotation because # why not ) variable: ( because # why not ) # output def f( a, ): d = { "key": "value", } tup = (1,) def f2( a, b, ): d = { "key": "value", "key2": "value2", } tup = ( 1, 2, ) def f( a: int = 1, ): call( arg={ "explode": "this", } ) call2( arg=[1, 2, 3], ) x = { "a": 1, "b": 2, }["a"] if ( a == { "a": 1, "b": 2, "c": 3, "d": 4, "e": 5, "f": 6, "g": 7, "h": 8, }["a"] ): pass def xxxxxxxxxxxxxxxxxxxxxxxxxxxx() -> ( Set["xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"] ): json = { "k": { "k2": { "k3": [ 1, ] } } } # The type annotation shouldn't get a trailing comma since that would change its type. # Relevant bug report: https://github.com/psf/black/issues/2381. def some_function_with_a_really_long_name() -> ( returning_a_deeply_nested_import_of_a_type_i_suppose ): pass def some_method_with_a_really_long_name( very_long_parameter_so_yeah: str, another_long_parameter: int ) -> another_case_of_returning_a_deeply_nested_import_of_a_type_i_suppose_cause_why_not: pass def func() -> ( also_super_long_type_annotation_that_may_cause_an_AST_related_crash_in_black( this_shouldn_t_get_a_trailing_comma_too ) ): pass def func() -> ( also_super_long_type_annotation_that_may_cause_an_AST_related_crash_in_black( this_shouldn_t_get_a_trailing_comma_too ) ): pass # Make sure inner one-element tuple won't explode some_module.some_function( argument1, (one_element_tuple,), argument4, argument5, argument6 ) # Inner trailing comma causes outer to explode some_module.some_function( argument1, ( one, two, ), argument4, argument5, argument6, ) def foo() -> ( # comment inside parenthesised return type int ): ... def foo() -> ( # comment inside parenthesised return type # more int # another ): ... def foo() -> ( # comment inside parenthesised new union return type int | str | bytes ): ... def foo() -> ( # comment inside plain tuple ): pass def foo( arg: ( # comment with non-return annotation int # comment with non-return annotation ), ): pass def foo( arg: ( # comment with non-return annotation int | range | memoryview # comment with non-return annotation ), ): pass def foo(arg: int): # only before pass def foo( arg: ( int # only after ), ): pass variable: ( # annotation because # why not ) variable: ( because # why not )
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/pep_646.py
tests/data/cases/pep_646.py
# flags: --minimum-version=3.11 A[*b] A[*b] = 1 A del A[*b] A A[*b, *b] A[*b, *b] = 1 A del A[*b, *b] A A[b, *b] A[b, *b] = 1 A del A[b, *b] A A[*b, b] A[*b, b] = 1 A del A[*b, b] A A[b, b, *b] A[b, b, *b] = 1 A del A[b, b, *b] A A[*b, b, b] A[*b, b, b] = 1 A del A[*b, b, b] A A[b, *b, b] A[b, *b, b] = 1 A del A[b, *b, b] A A[b, b, *b, b] A[b, b, *b, b] = 1 A del A[b, b, *b, b] A A[b, *b, b, b] A[b, *b, b, b] = 1 A del A[b, *b, b, b] A A[A[b, *b, b]] A[A[b, *b, b]] = 1 A del A[A[b, *b, b]] A A[*A[b, *b, b]] A[*A[b, *b, b]] = 1 A del A[*A[b, *b, b]] A A[b, ...] A[b, ...] = 1 A del A[b, ...] A A[*A[b, ...]] A[*A[b, ...]] = 1 A del A[*A[b, ...]] A l = [1, 2, 3] A[*l] A[*l] = 1 A del A[*l] A A[*l, 4] A[*l, 4] = 1 A del A[*l, 4] A A[0, *l] A[0, *l] = 1 A del A[0, *l] A A[1:2, *l] A[1:2, *l] = 1 A del A[1:2, *l] A repr(A[1:2, *l]) == repr(A[1:2, 1, 2, 3]) t = (1, 2, 3) A[*t] A[*t] = 1 A del A[*t] A A[*t, 4] A[*t, 4] = 1 A del A[*t, 4] A A[0, *t] A[0, *t] = 1 A del A[0, *t] A A[1:2, *t] A[1:2, *t] = 1 A del A[1:2, *t] A repr(A[1:2, *t]) == repr(A[1:2, 1, 2, 3]) def returns_list(): return [1, 2, 3] A[returns_list()] A[returns_list()] = 1 A del A[returns_list()] A A[returns_list(), 4] A[returns_list(), 4] = 1 A del A[returns_list(), 4] A A[*returns_list()] A[*returns_list()] = 1 A del A[*returns_list()] A A[*returns_list(), 4] A[*returns_list(), 4] = 1 A del A[*returns_list(), 4] A A[0, *returns_list()] A[0, *returns_list()] = 1 A del A[0, *returns_list()] A A[*returns_list(), *returns_list()] A[*returns_list(), *returns_list()] = 1 A del A[*returns_list(), *returns_list()] A A[1:2, *b] A[*b, 1:2] A[1:2, *b, 1:2] A[*b, 1:2, *b] A[1:, *b] A[*b, 1:] A[1:, *b, 1:] A[*b, 1:, *b] A[:1, *b] A[*b, :1] A[:1, *b, :1] A[*b, :1, *b] A[:, *b] A[*b, :] A[:, *b, :] A[*b, :, *b] A[a * b()] A[a * b(), *c, *d(), e * f(g * h)] A[a * b(), :] A[a * b(), *c, *d(), e * f(g * h) :] A[[b] * len(c), :] def f1(*args: *b): pass f1.__annotations__ def f2(*args: *b, arg1): pass f2.__annotations__ def f3(*args: *b, arg1: int): pass f3.__annotations__ def f4(*args: *b, arg1: int = 2): pass f4.__annotations__
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/fmtskip9.py
tests/data/cases/fmtskip9.py
print () # fmt: skip print () # fmt:skip # output print () # fmt: skip print () # fmt:skip
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/preview_hug_parens_with_braces_and_square_brackets_no_ll1.py
tests/data/cases/preview_hug_parens_with_braces_and_square_brackets_no_ll1.py
# flags: --unstable --no-preview-line-length-1 # split out from preview_hug_parens_with_brackes_and_square_brackets, as it produces # different code on the second pass with line-length 1 in many cases. # Seems to be about whether the last string in a sequence gets wrapped in parens or not. foo(*["long long long long long line", "long long long long long line", "long long long long long line"]) func({"short line"}) func({"long line", "long long line", "long long long line", "long long long long line", "long long long long long line"}) func({{"long line", "long long line", "long long long line", "long long long long line", "long long long long long line"}}) func(("long line", "long long line", "long long long line", "long long long long line", "long long long long long line")) func((("long line", "long long line", "long long long line", "long long long long line", "long long long long long line"))) func([["long line", "long long line", "long long long line", "long long long long line", "long long long long long line"]]) # Do not hug if the argument fits on a single line. func({"fit line", "fit line", "fit line", "fit line", "fit line", "fit line", "fit line"}) func(("fit line", "fit line", "fit line", "fit line", "fit line", "fit line", "fit line")) func(["fit line", "fit line", "fit line", "fit line", "fit line", "fit line", "fit line"]) func(**{"fit line", "fit line", "fit line", "fit line", "fit line", "fit line", "fit---"}) func(*("fit line", "fit line", "fit line", "fit line", "fit line", "fit line", "fit----")) array = [{"fit line", "fit line", "fit line", "fit line", "fit line", "fit line", "fit line"}] array = [("fit line", "fit line", "fit line", "fit line", "fit line", "fit line", "fit line")] array = [["fit line", "fit line", "fit line", "fit line", "fit line", "fit line", "fit line"]] nested_array = [[["long line", "long long line", "long long long line", "long long long long line", "long long long long long line"]]] # output # split out from preview_hug_parens_with_brackes_and_square_brackets, as it produces # different code on the second pass with line-length 1 in many cases. # Seems to be about whether the last string in a sequence gets wrapped in parens or not. foo(*[ "long long long long long line", "long long long long long line", "long long long long long line", ]) func({"short line"}) func({ "long line", "long long line", "long long long line", "long long long long line", "long long long long long line", }) func({{ "long line", "long long line", "long long long line", "long long long long line", "long long long long long line", }}) func(( "long line", "long long line", "long long long line", "long long long long line", "long long long long long line", )) func((( "long line", "long long line", "long long long line", "long long long long line", "long long long long long line", ))) func([[ "long line", "long long line", "long long long line", "long long long long line", "long long long long long line", ]]) # Do not hug if the argument fits on a single line. func( {"fit line", "fit line", "fit line", "fit line", "fit line", "fit line", "fit line"} ) func( ("fit line", "fit line", "fit line", "fit line", "fit line", "fit line", "fit line") ) func( ["fit line", "fit line", "fit line", "fit line", "fit line", "fit line", "fit line"] ) func( **{"fit line", "fit line", "fit line", "fit line", "fit line", "fit line", "fit---"} ) func( *("fit line", "fit line", "fit line", "fit line", "fit line", "fit line", "fit----") ) array = [ {"fit line", "fit line", "fit line", "fit line", "fit line", "fit line", "fit line"} ] array = [ ("fit line", "fit line", "fit line", "fit line", "fit line", "fit line", "fit line") ] array = [ ["fit line", "fit line", "fit line", "fit line", "fit line", "fit line", "fit line"] ] nested_array = [[[ "long line", "long long line", "long long long line", "long long long long line", "long long long long long line", ]]]
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/line_ranges_indentation.py
tests/data/cases/line_ranges_indentation.py
# flags: --line-ranges=5-5 # NOTE: If you need to modify this file, pay special attention to the --line-ranges= # flag above as it's formatting specifically these lines. if cond1: print("first") if cond2: print("second") else: print("else") if another_cond: print("will not be changed") # output # flags: --line-ranges=5-5 # NOTE: If you need to modify this file, pay special attention to the --line-ranges= # flag above as it's formatting specifically these lines. if cond1: print("first") if cond2: print("second") else: print("else") if another_cond: print("will not be changed")
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/context_managers_38.py
tests/data/cases/context_managers_38.py
with \ make_context_manager1() as cm1, \ make_context_manager2() as cm2, \ make_context_manager3() as cm3, \ make_context_manager4() as cm4 \ : pass with \ make_context_manager1() as cm1, \ make_context_manager2(), \ make_context_manager3() as cm3, \ make_context_manager4() \ : pass with \ new_new_new1() as cm1, \ new_new_new2() \ : pass with mock.patch.object( self.my_runner, "first_method", autospec=True ) as mock_run_adb, mock.patch.object( self.my_runner, "second_method", autospec=True, return_value="foo" ): pass # output with make_context_manager1() as cm1, make_context_manager2() as cm2, make_context_manager3() as cm3, make_context_manager4() as cm4: pass with make_context_manager1() as cm1, make_context_manager2(), make_context_manager3() as cm3, make_context_manager4(): pass with new_new_new1() as cm1, new_new_new2(): pass with mock.patch.object( self.my_runner, "first_method", autospec=True ) as mock_run_adb, mock.patch.object( self.my_runner, "second_method", autospec=True, return_value="foo" ): pass
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/preview_standardize_type_comments.py
tests/data/cases/preview_standardize_type_comments.py
# flags: --preview def foo( a, #type:int b, #type: str c, # type: List[int] d, # type: Dict[int, str] e, # type: ignore f, # type : ignore g, # type : ignore ): pass # output def foo( a, # type: int b, # type: str c, # type: List[int] d, # type: Dict[int, str] e, # type: ignore f, # type : ignore g, # type : ignore ): pass
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/py310_pep572.py
tests/data/cases/py310_pep572.py
# flags: --minimum-version=3.10 x[a:=0] x[a := 0] x[a := 0, b := 1] x[5, b := 0] x[a:=0,b:=1] # output x[a := 0] x[a := 0] x[a := 0, b := 1] x[5, b := 0] x[a := 0, b := 1]
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/pep646_typed_star_arg_type_var_tuple.py
tests/data/cases/pep646_typed_star_arg_type_var_tuple.py
# flags: --minimum-version=3.11 def fn(*args: *tuple[*A, B]) -> None: pass fn.__annotations__
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/empty_lines.py
tests/data/cases/empty_lines.py
"""Docstring.""" # leading comment def f(): NO = '' SPACE = ' ' DOUBLESPACE = ' ' t = leaf.type p = leaf.parent # trailing comment v = leaf.value if t in ALWAYS_NO_SPACE: pass if t == token.COMMENT: # another trailing comment return DOUBLESPACE assert p is not None, f"INTERNAL ERROR: hand-made leaf without parent: {leaf!r}" prev = leaf.prev_sibling if not prev: prevp = preceding_leaf(p) if not prevp or prevp.type in OPENING_BRACKETS: return NO if prevp.type == token.EQUAL: if prevp.parent and prevp.parent.type in { syms.typedargslist, syms.varargslist, syms.parameters, syms.arglist, syms.argument, }: return NO elif prevp.type == token.DOUBLESTAR: if prevp.parent and prevp.parent.type in { syms.typedargslist, syms.varargslist, syms.parameters, syms.arglist, syms.dictsetmaker, }: return NO ############################################################################### # SECTION BECAUSE SECTIONS ############################################################################### def g(): NO = '' SPACE = ' ' DOUBLESPACE = ' ' t = leaf.type p = leaf.parent v = leaf.value # Comment because comments if t in ALWAYS_NO_SPACE: pass if t == token.COMMENT: return DOUBLESPACE # Another comment because more comments assert p is not None, f'INTERNAL ERROR: hand-made leaf without parent: {leaf!r}' prev = leaf.prev_sibling if not prev: prevp = preceding_leaf(p) if not prevp or prevp.type in OPENING_BRACKETS: # Start of the line or a bracketed expression. # More than one line for the comment. return NO if prevp.type == token.EQUAL: if prevp.parent and prevp.parent.type in { syms.typedargslist, syms.varargslist, syms.parameters, syms.arglist, syms.argument, }: return NO # output """Docstring.""" # leading comment def f(): NO = "" SPACE = " " DOUBLESPACE = " " t = leaf.type p = leaf.parent # trailing comment v = leaf.value if t in ALWAYS_NO_SPACE: pass if t == token.COMMENT: # another trailing comment return DOUBLESPACE assert p is not None, f"INTERNAL ERROR: hand-made leaf without parent: {leaf!r}" prev = leaf.prev_sibling if not prev: prevp = preceding_leaf(p) if not prevp or prevp.type in OPENING_BRACKETS: return NO if prevp.type == token.EQUAL: if prevp.parent and prevp.parent.type in { syms.typedargslist, syms.varargslist, syms.parameters, syms.arglist, syms.argument, }: return NO elif prevp.type == token.DOUBLESTAR: if prevp.parent and prevp.parent.type in { syms.typedargslist, syms.varargslist, syms.parameters, syms.arglist, syms.dictsetmaker, }: return NO ############################################################################### # SECTION BECAUSE SECTIONS ############################################################################### def g(): NO = "" SPACE = " " DOUBLESPACE = " " t = leaf.type p = leaf.parent v = leaf.value # Comment because comments if t in ALWAYS_NO_SPACE: pass if t == token.COMMENT: return DOUBLESPACE # Another comment because more comments assert p is not None, f"INTERNAL ERROR: hand-made leaf without parent: {leaf!r}" prev = leaf.prev_sibling if not prev: prevp = preceding_leaf(p) if not prevp or prevp.type in OPENING_BRACKETS: # Start of the line or a bracketed expression. # More than one line for the comment. return NO if prevp.type == token.EQUAL: if prevp.parent and prevp.parent.type in { syms.typedargslist, syms.varargslist, syms.parameters, syms.arglist, syms.argument, }: return NO
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/conditional_expression.py
tests/data/cases/conditional_expression.py
long_kwargs_single_line = my_function( foo="test, this is a sample value", bar=some_long_value_name_foo_bar_baz if some_boolean_variable else some_fallback_value_foo_bar_baz, baz="hello, this is a another value", ) multiline_kwargs_indented = my_function( foo="test, this is a sample value", bar=some_long_value_name_foo_bar_baz if some_boolean_variable else some_fallback_value_foo_bar_baz, baz="hello, this is a another value", ) imploding_kwargs = my_function( foo="test, this is a sample value", bar=a if foo else b, baz="hello, this is a another value", ) imploding_line = ( 1 if 1 + 1 == 2 else 0 ) exploding_line = "hello this is a slightly long string" if some_long_value_name_foo_bar_baz else "this one is a little shorter" positional_argument_test(some_long_value_name_foo_bar_baz if some_boolean_variable else some_fallback_value_foo_bar_baz) def weird_default_argument(x=some_long_value_name_foo_bar_baz if SOME_CONSTANT else some_fallback_value_foo_bar_baz): pass nested = "hello this is a slightly long string" if (some_long_value_name_foo_bar_baz if nesting_test_expressions else some_fallback_value_foo_bar_baz) \ else "this one is a little shorter" generator_expression = ( some_long_value_name_foo_bar_baz if some_boolean_variable else some_fallback_value_foo_bar_baz for some_boolean_variable in some_iterable ) def limit_offset_sql(self, low_mark, high_mark): """Return LIMIT/OFFSET SQL clause.""" limit, offset = self._get_limit_offset_params(low_mark, high_mark) return " ".join( sql for sql in ( "LIMIT %d" % limit if limit else None, ("OFFSET %d" % offset) if offset else None, ) if sql ) def something(): clone._iterable_class = ( NamedValuesListIterable if named else FlatValuesListIterable if flat else ValuesListIterable ) def foo(wait: bool = True): # This comment is two # lines long # This is only one time.sleep(1) if wait else None time.sleep(1) if wait else None # With newline above time.sleep(1) if wait else None # Without newline above time.sleep(1) if wait else None a = "".join( ( "", # comment "" if True else "", ) ) # output long_kwargs_single_line = my_function( foo="test, this is a sample value", bar=( some_long_value_name_foo_bar_baz if some_boolean_variable else some_fallback_value_foo_bar_baz ), baz="hello, this is a another value", ) multiline_kwargs_indented = my_function( foo="test, this is a sample value", bar=( some_long_value_name_foo_bar_baz if some_boolean_variable else some_fallback_value_foo_bar_baz ), baz="hello, this is a another value", ) imploding_kwargs = my_function( foo="test, this is a sample value", bar=a if foo else b, baz="hello, this is a another value", ) imploding_line = 1 if 1 + 1 == 2 else 0 exploding_line = ( "hello this is a slightly long string" if some_long_value_name_foo_bar_baz else "this one is a little shorter" ) positional_argument_test( some_long_value_name_foo_bar_baz if some_boolean_variable else some_fallback_value_foo_bar_baz ) def weird_default_argument( x=( some_long_value_name_foo_bar_baz if SOME_CONSTANT else some_fallback_value_foo_bar_baz ), ): pass nested = ( "hello this is a slightly long string" if ( some_long_value_name_foo_bar_baz if nesting_test_expressions else some_fallback_value_foo_bar_baz ) else "this one is a little shorter" ) generator_expression = ( ( some_long_value_name_foo_bar_baz if some_boolean_variable else some_fallback_value_foo_bar_baz ) for some_boolean_variable in some_iterable ) def limit_offset_sql(self, low_mark, high_mark): """Return LIMIT/OFFSET SQL clause.""" limit, offset = self._get_limit_offset_params(low_mark, high_mark) return " ".join( sql for sql in ( "LIMIT %d" % limit if limit else None, ("OFFSET %d" % offset) if offset else None, ) if sql ) def something(): clone._iterable_class = ( NamedValuesListIterable if named else FlatValuesListIterable if flat else ValuesListIterable ) def foo(wait: bool = True): # This comment is two # lines long # This is only one time.sleep(1) if wait else None time.sleep(1) if wait else None # With newline above time.sleep(1) if wait else None # Without newline above time.sleep(1) if wait else None a = "".join( ( "", # comment "" if True else "", ) )
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/remove_parens_from_lhs.py
tests/data/cases/remove_parens_from_lhs.py
# flags: --preview # Remove unnecessary parentheses from LHS of assignments def a(): return [1, 2, 3] # Single variable with unnecessary parentheses (b) = a()[0] # Tuple unpacking with unnecessary parentheses (c, *_) = a() # These should not be changed - parentheses are necessary (d,) = a() # single-element tuple e = (1 + 2) * 3 # RHS has precedence needs # output # Remove unnecessary parentheses from LHS of assignments def a(): return [1, 2, 3] # Single variable with unnecessary parentheses b = a()[0] # Tuple unpacking with unnecessary parentheses c, *_ = a() # These should not be changed - parentheses are necessary (d,) = a() # single-element tuple e = (1 + 2) * 3 # RHS has precedence needs
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/pep_654.py
tests/data/cases/pep_654.py
# flags: --minimum-version=3.11 try: raise OSError("blah") except* ExceptionGroup as e: pass try: async with trio.open_nursery() as nursery: # Make two concurrent calls to child() nursery.start_soon(child) nursery.start_soon(child) except* ValueError: pass try: try: raise ValueError(42) except: try: raise TypeError(int) except* Exception: pass 1 / 0 except Exception as e: exc = e try: try: raise FalsyEG("eg", [TypeError(1), ValueError(2)]) except* TypeError as e: tes = e raise except* ValueError as e: ves = e pass except Exception as e: exc = e try: try: raise orig except* (TypeError, ValueError) as e: raise SyntaxError(3) from e except BaseException as e: exc = e try: try: raise orig except* OSError as e: raise TypeError(3) from e except ExceptionGroup as e: exc = e
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/line_ranges_two_passes.py
tests/data/cases/line_ranges_two_passes.py
# flags: --line-ranges=9-11 # NOTE: If you need to modify this file, pay special attention to the --line-ranges= # flag above as it's formatting specifically these lines. # This is a specific case for Black's two-pass formatting behavior in `format_str`. # The second pass must respect the line ranges before the first pass. def restrict_to_this_line(arg1, arg2, arg3): print ( "This should not be formatted." ) print ( "Note that in the second pass, the original line range 9-11 will cover these print lines.") # output # flags: --line-ranges=9-11 # NOTE: If you need to modify this file, pay special attention to the --line-ranges= # flag above as it's formatting specifically these lines. # This is a specific case for Black's two-pass formatting behavior in `format_str`. # The second pass must respect the line ranges before the first pass. def restrict_to_this_line(arg1, arg2, arg3): print ( "This should not be formatted." ) print ( "Note that in the second pass, the original line range 9-11 will cover these print lines.")
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/comments3.py
tests/data/cases/comments3.py
# The percent-percent comments are Spyder IDE cells. # %% def func(): x = """ a really long string """ lcomp3 = [ # This one is actually too long to fit in a single line. element.split("\n", 1)[0] # yup for element in collection.select_elements() # right if element is not None ] # Capture each of the exceptions in the MultiError along with each of their causes and contexts if isinstance(exc_value, MultiError): embedded = [] for exc in exc_value.exceptions: if exc not in _seen: embedded.append( # This should be left alone (before) traceback.TracebackException.from_exception( exc, limit=limit, lookup_lines=lookup_lines, capture_locals=capture_locals, # copy the set of _seen exceptions so that duplicates # shared between sub-exceptions are not omitted _seen=set(_seen), ) # This should be left alone (after) ) # everything is fine if the expression isn't nested traceback.TracebackException.from_exception( exc, limit=limit, lookup_lines=lookup_lines, capture_locals=capture_locals, # copy the set of _seen exceptions so that duplicates # shared between sub-exceptions are not omitted _seen=set(_seen), ) # %%
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/line_ranges_basic.py
tests/data/cases/line_ranges_basic.py
# flags: --line-ranges=5-6 # NOTE: If you need to modify this file, pay special attention to the --line-ranges= # flag above as it's formatting specifically these lines. def foo1(parameter_1, parameter_2, parameter_3, parameter_4, parameter_5, parameter_6, parameter_7): pass def foo2(parameter_1, parameter_2, parameter_3, parameter_4, parameter_5, parameter_6, parameter_7): pass def foo3(parameter_1, parameter_2, parameter_3, parameter_4, parameter_5, parameter_6, parameter_7): pass def foo4(parameter_1, parameter_2, parameter_3, parameter_4, parameter_5, parameter_6, parameter_7): pass # Adding some unformated code covering a wide range of syntaxes. if True: # Incorrectly indented prefix comments. pass import typing from typing import ( Any , ) class MyClass( object): # Trailing comment with extra leading space. #NOTE: The following indentation is incorrect: @decor( 1 * 3 ) def my_func( arg): pass try: # Trailing comment with extra leading space. for i in range(10): # Trailing comment with extra leading space. while condition: if something: then_something( ) elif something_else: then_something_else( ) except ValueError as e: unformatted( ) finally: unformatted( ) async def test_async_unformatted( ): # Trailing comment with extra leading space. async for i in some_iter( unformatted ): # Trailing comment with extra leading space. await asyncio.sleep( 1 ) async with some_context( unformatted ): print( "unformatted" ) # output # flags: --line-ranges=5-6 # NOTE: If you need to modify this file, pay special attention to the --line-ranges= # flag above as it's formatting specifically these lines. def foo1(parameter_1, parameter_2, parameter_3, parameter_4, parameter_5, parameter_6, parameter_7): pass def foo2( parameter_1, parameter_2, parameter_3, parameter_4, parameter_5, parameter_6, parameter_7, ): pass def foo3( parameter_1, parameter_2, parameter_3, parameter_4, parameter_5, parameter_6, parameter_7, ): pass def foo4(parameter_1, parameter_2, parameter_3, parameter_4, parameter_5, parameter_6, parameter_7): pass # Adding some unformated code covering a wide range of syntaxes. if True: # Incorrectly indented prefix comments. pass import typing from typing import ( Any , ) class MyClass( object): # Trailing comment with extra leading space. #NOTE: The following indentation is incorrect: @decor( 1 * 3 ) def my_func( arg): pass try: # Trailing comment with extra leading space. for i in range(10): # Trailing comment with extra leading space. while condition: if something: then_something( ) elif something_else: then_something_else( ) except ValueError as e: unformatted( ) finally: unformatted( ) async def test_async_unformatted( ): # Trailing comment with extra leading space. async for i in some_iter( unformatted ): # Trailing comment with extra leading space. await asyncio.sleep( 1 ) async with some_context( unformatted ): print( "unformatted" )
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/ignore_pyi.py
tests/data/cases/ignore_pyi.py
# flags: --pyi def f(): # type: ignore ... class x: # some comment ... class y: ... # comment # whitespace doesn't matter (note the next line has a trailing space and tab) class z: ... def g(): # hi ... def h(): ... # bye # output def f(): # type: ignore ... class x: # some comment ... class y: ... # comment # whitespace doesn't matter (note the next line has a trailing space and tab) class z: ... def g(): # hi ... def h(): ... # bye
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/pattern_matching_with_if_stmt.py
tests/data/cases/pattern_matching_with_if_stmt.py
# flags: --minimum-version=3.10 match match: case "test" if case != "not very loooooooooooooog condition": # comment pass match smth: case "test" if "any long condition" != "another long condition" and "this is a long condition": pass case test if "any long condition" != "another long condition" and "this is a looooong condition": pass case test if "any long condition" != "another long condition" and "this is a looooong condition": # some additional comments pass case test if (True): # some comment pass case test if (False ): # some comment pass case test if (True # some comment ): pass # some comment case cases if (True # some comment ): # some other comment pass # some comment case match if (True # some comment ): pass # some comment # case black_test_patma_052 (originally in the pattern_matching_complex test case) match x: case [1, 0] if x := x[:0]: y = 1 case [1, 0] if (x := x[:0]): y = 1 # output match match: case "test" if case != "not very loooooooooooooog condition": # comment pass match smth: case "test" if ( "any long condition" != "another long condition" and "this is a long condition" ): pass case test if ( "any long condition" != "another long condition" and "this is a looooong condition" ): pass case test if ( "any long condition" != "another long condition" and "this is a looooong condition" ): # some additional comments pass case test if True: # some comment pass case test if False: # some comment pass case test if True: # some comment pass # some comment case cases if True: # some comment # some other comment pass # some comment case match if True: # some comment pass # some comment # case black_test_patma_052 (originally in the pattern_matching_complex test case) match x: case [1, 0] if x := x[:0]: y = 1 case [1, 0] if x := x[:0]: y = 1
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/skip_magic_trailing_comma.py
tests/data/cases/skip_magic_trailing_comma.py
# flags: --skip-magic-trailing-comma # We should not remove the trailing comma in a single-element subscript. a: tuple[int,] b = tuple[int,] # But commas in multiple element subscripts should be removed. c: tuple[int, int,] d = tuple[int, int,] # Remove commas for non-subscripts. small_list = [1,] list_of_types = [tuple[int,],] small_set = {1,} set_of_types = {tuple[int,],} # Except single element tuples small_tuple = (1,) # Trailing commas in multiple chained non-nested parens. zero( one, ).two( three, ).four( five, ) func1(arg1).func2(arg2,).func3(arg3).func4(arg4,).func5(arg5) ( a, b, c, d, ) = func1( arg1 ) and func2(arg2) func( argument1, ( one, two, ), argument4, argument5, argument6, ) # output # We should not remove the trailing comma in a single-element subscript. a: tuple[int,] b = tuple[int,] # But commas in multiple element subscripts should be removed. c: tuple[int, int] d = tuple[int, int] # Remove commas for non-subscripts. small_list = [1] list_of_types = [tuple[int,]] small_set = {1} set_of_types = {tuple[int,]} # Except single element tuples small_tuple = (1,) # Trailing commas in multiple chained non-nested parens. zero(one).two(three).four(five) func1(arg1).func2(arg2).func3(arg3).func4(arg4).func5(arg5) (a, b, c, d) = func1(arg1) and func2(arg2) func(argument1, (one, two), argument4, argument5, argument6)
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/comments8.py
tests/data/cases/comments8.py
# The percent-percent comments are Spyder IDE cells. # Both `#%%`` and `# %%` are accepted, so `black` standardises # to the latter. #%% # %% # output # The percent-percent comments are Spyder IDE cells. # Both `#%%`` and `# %%` are accepted, so `black` standardises # to the latter. # %% # %%
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/line_ranges_fmt_off_overlap.py
tests/data/cases/line_ranges_fmt_off_overlap.py
# flags: --line-ranges=11-17 # NOTE: If you need to modify this file, pay special attention to the --line-ranges= # flag above as it's formatting specifically these lines. def myfunc( ): # This will not be reformatted. print( {"also won't be reformatted"} ) # fmt: off def myfunc( ): # This will not be reformatted. print( {"also won't be reformatted"} ) def myfunc( ): # This will not be reformatted. print( {"also won't be reformatted"} ) # fmt: on def myfunc( ): # This will be reformatted. print( {"this will be reformatted"} ) # output # flags: --line-ranges=11-17 # NOTE: If you need to modify this file, pay special attention to the --line-ranges= # flag above as it's formatting specifically these lines. def myfunc( ): # This will not be reformatted. print( {"also won't be reformatted"} ) # fmt: off def myfunc( ): # This will not be reformatted. print( {"also won't be reformatted"} ) def myfunc( ): # This will not be reformatted. print( {"also won't be reformatted"} ) # fmt: on def myfunc(): # This will be reformatted. print({"this will be reformatted"})
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/type_param_defaults.py
tests/data/cases/type_param_defaults.py
# flags: --minimum-version=3.13 type A[T=int] = float type B[*P=int] = float type C[*Ts=int] = float type D[*Ts=*int] = float type D[something_that_is_very_very_very_long=something_that_is_very_very_very_long] = float type D[*something_that_is_very_very_very_long=*something_that_is_very_very_very_long] = float type something_that_is_long[something_that_is_long=something_that_is_long] = something_that_is_long def simple[T=something_that_is_long](short1: int, short2: str, short3: bytes) -> float: pass def longer[something_that_is_long=something_that_is_long](something_that_is_long: something_that_is_long) -> something_that_is_long: pass def trailing_comma1[T=int,](a: str): pass def trailing_comma2[T=int](a: str,): pass def weird_syntax[T=lambda: 42, **P=lambda: 43, *Ts=lambda: 44](): pass # output type A[T = int] = float type B[*P = int] = float type C[*Ts = int] = float type D[*Ts = *int] = float type D[ something_that_is_very_very_very_long = something_that_is_very_very_very_long ] = float type D[ *something_that_is_very_very_very_long = *something_that_is_very_very_very_long ] = float type something_that_is_long[ something_that_is_long = something_that_is_long ] = something_that_is_long def simple[T = something_that_is_long]( short1: int, short2: str, short3: bytes ) -> float: pass def longer[something_that_is_long = something_that_is_long]( something_that_is_long: something_that_is_long, ) -> something_that_is_long: pass def trailing_comma1[ T = int, ]( a: str, ): pass def trailing_comma2[T = int]( a: str, ): pass def weird_syntax[T = lambda: 42, **P = lambda: 43, *Ts = lambda: 44](): pass
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/preview_cantfit_string.py
tests/data/cases/preview_cantfit_string.py
# flags: --unstable # long arguments normal_name = normal_function_name( "but with super long string arguments that on their own exceed the line limit so there's no way it can ever fit", "eggs with spam and eggs and spam with eggs with spam and eggs and spam with eggs with spam and eggs and spam with eggs", this_is_a_ridiculously_long_name_and_nobody_in_their_right_mind_would_use_one_like_it=0, ) # output # long arguments normal_name = normal_function_name( "but with super long string arguments that on their own exceed the line limit so" " there's no way it can ever fit", "eggs with spam and eggs and spam with eggs with spam and eggs and spam with eggs" " with spam and eggs and spam with eggs", this_is_a_ridiculously_long_name_and_nobody_in_their_right_mind_would_use_one_like_it=0, )
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/pep_572_remove_parens.py
tests/data/cases/pep_572_remove_parens.py
if (foo := 0): pass if (foo := 1): pass if (y := 5 + 5): pass y = (x := 0) y += (x := 0) (y := 5 + 5) test: int = (test2 := 2) a, b = (test := (1, 2)) # see also https://github.com/psf/black/issues/2139 assert (foo := 42 - 12) foo(x=(y := f(x))) def foo(answer=(p := 42)): ... def foo2(answer: (p := 42) = 5): ... lambda: (x := 1) a[(x := 12)] a[:(x := 13)] # we don't touch expressions in f-strings but if we do one day, don't break 'em f'{(x:=10)}' def a(): return (x := 3) await (b := 1) yield (a := 2) raise (c := 3) def this_is_so_dumb() -> (please := no): pass async def await_the_walrus(): with (x := y): pass with (x := y) as z, (a := b) as c: pass with (x := await y): pass with (x := await a, y := await b): pass with ((x := await a, y := await b)): pass with (x := await a), (y := await b): pass # output if foo := 0: pass if foo := 1: pass if y := 5 + 5: pass y = (x := 0) y += (x := 0) (y := 5 + 5) test: int = (test2 := 2) a, b = (test := (1, 2)) # see also https://github.com/psf/black/issues/2139 assert (foo := 42 - 12) foo(x=(y := f(x))) def foo(answer=(p := 42)): ... def foo2(answer: (p := 42) = 5): ... lambda: (x := 1) a[(x := 12)] a[: (x := 13)] # we don't touch expressions in f-strings but if we do one day, don't break 'em f"{(x:=10)}" def a(): return (x := 3) await (b := 1) yield (a := 2) raise (c := 3) def this_is_so_dumb() -> (please := no): pass async def await_the_walrus(): with (x := y): pass with (x := y) as z, (a := b) as c: pass with (x := await y): pass with (x := await a, y := await b): pass with (x := await a, y := await b): pass with (x := await a), (y := await b): pass
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/whitespace.py
tests/data/cases/whitespace.py
# output
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/pep_572.py
tests/data/cases/pep_572.py
(a := 1) (a := a) if (match := pattern.search(data)) is None: pass if match := pattern.search(data): pass [y := f(x), y**2, y**3] filtered_data = [y for x in data if (y := f(x)) is None] (y := f(x)) y0 = (y1 := f(x)) foo(x=(y := f(x))) def foo(answer=(p := 42)): pass def foo(answer: (p := 42) = 5): pass lambda: (x := 1) (x := lambda: 1) (x := lambda: (y := 1)) lambda line: (m := re.match(pattern, line)) and m.group(1) x = (y := 0) (z := (y := (x := 0))) (info := (name, phone, *rest)) (x := 1, 2) (total := total + tax) len(lines := f.readlines()) foo(x := 3, cat="vector") foo(cat=(category := "vector")) if any(len(longline := l) >= 100 for l in lines): print(longline) if env_base := os.environ.get("PYTHONUSERBASE", None): return env_base if self._is_special and (ans := self._check_nans(context=context)): return ans foo(b := 2, a=1) foo((b := 2), a=1) foo(c=(b := 2), a=1) while x := f(x): pass while x := f(x): pass
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/remove_except_types_parens_pre_py314.py
tests/data/cases/remove_except_types_parens_pre_py314.py
# flags: --preview --minimum-version=3.11 # SEE PEP 758 FOR MORE DETAILS # remains unchanged try: pass except: pass # remains unchanged try: pass except ValueError: pass try: pass except* ValueError: pass # parenthesis are removed try: pass except (ValueError): pass try: pass except* (ValueError): pass # parenthesis are removed try: pass except (ValueError) as e: pass try: pass except* (ValueError) as e: pass # remains unchanged try: pass except (ValueError,): pass try: pass except* (ValueError,): pass # remains unchanged try: pass except (ValueError,) as e: pass try: pass except* (ValueError,) as e: pass # parenthesis are not removed try: pass except (ValueError, TypeError, KeyboardInterrupt): pass try: pass except* (ValueError, TypeError, KeyboardInterrupt): pass # parenthesis are not removed try: pass except (ValueError, TypeError, KeyboardInterrupt) as e: pass try: pass except* (ValueError, TypeError, KeyboardInterrupt) as e: pass # parenthesis are removed try: pass except (ValueError if True else TypeError): pass try: pass except* (ValueError if True else TypeError): pass # parenthesis are not removed try: try: pass except (TypeError, KeyboardInterrupt): pass except (ValueError,): pass try: try: pass except* (TypeError, KeyboardInterrupt): pass except* (ValueError,): pass # output # SEE PEP 758 FOR MORE DETAILS # remains unchanged try: pass except: pass # remains unchanged try: pass except ValueError: pass try: pass except* ValueError: pass # parenthesis are removed try: pass except ValueError: pass try: pass except* ValueError: pass # parenthesis are removed try: pass except ValueError as e: pass try: pass except* ValueError as e: pass # remains unchanged try: pass except (ValueError,): pass try: pass except* (ValueError,): pass # remains unchanged try: pass except (ValueError,) as e: pass try: pass except* (ValueError,) as e: pass # parenthesis are not removed try: pass except (ValueError, TypeError, KeyboardInterrupt): pass try: pass except* (ValueError, TypeError, KeyboardInterrupt): pass # parenthesis are not removed try: pass except (ValueError, TypeError, KeyboardInterrupt) as e: pass try: pass except* (ValueError, TypeError, KeyboardInterrupt) as e: pass # parenthesis are removed try: pass except ValueError if True else TypeError: pass try: pass except* ValueError if True else TypeError: pass # parenthesis are not removed try: try: pass except (TypeError, KeyboardInterrupt): pass except (ValueError,): pass try: try: pass except* (TypeError, KeyboardInterrupt): pass except* (ValueError,): pass
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/typed_params_trailing_comma.py
tests/data/cases/typed_params_trailing_comma.py
def long_function_name_goes_here( x: Callable[List[int]] ) -> Union[List[int], float, str, bytes, Tuple[int]]: pass def long_function_name_goes_here( x: Callable[[str, Any], int] ) -> Union[List[int], float, str, bytes, Tuple[int]]: pass # output def long_function_name_goes_here( x: Callable[List[int]], ) -> Union[List[int], float, str, bytes, Tuple[int]]: pass def long_function_name_goes_here( x: Callable[[str, Any], int], ) -> Union[List[int], float, str, bytes, Tuple[int]]: pass
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/context_managers_autodetect_310.py
tests/data/cases/context_managers_autodetect_310.py
# flags: --minimum-version=3.10 # This file uses pattern matching introduced in Python 3.10. match http_code: case 404: print("Not found") with \ make_context_manager1() as cm1, \ make_context_manager2() as cm2, \ make_context_manager3() as cm3, \ make_context_manager4() as cm4 \ : pass # output # This file uses pattern matching introduced in Python 3.10. match http_code: case 404: print("Not found") with ( make_context_manager1() as cm1, make_context_manager2() as cm2, make_context_manager3() as cm3, make_context_manager4() as cm4, ): pass
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/type_aliases.py
tests/data/cases/type_aliases.py
# flags: --minimum-version=3.12 type A=int type Gen[T]=list[T] type Alias[T]=lambda: T type And[T]=T and T type IfElse[T]=T if T else T type One = int; type Another = str class X: type InClass = int type = aliased print(type(42)) # output type A = int type Gen[T] = list[T] type Alias[T] = lambda: T type And[T] = T and T type IfElse[T] = T if T else T type One = int type Another = str class X: type InClass = int type = aliased print(type(42))
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/comments.py
tests/data/cases/comments.py
#!/usr/bin/env python3 # fmt: on # Some license here. # # Has many lines. Many, many lines. # Many, many, many lines. """Module docstring. Possibly also many, many lines. """ import os.path import sys import a from b.c import X # some noqa comment try: import fast except ImportError: import slow as fast # Some comment before a function. y = 1 ( # some strings y # type: ignore ) def function(default=None): """Docstring comes first. Possibly many lines. """ # FIXME: Some comment about why this function is crap but still in production. import inner_imports if inner_imports.are_evil(): # Explains why we have this if. # In great detail indeed. x = X() return x.method1() # type: ignore # This return is also commented for some reason. return default # Explains why we use global state. GLOBAL_STATE = {"a": a(1), "b": a(2), "c": a(3)} # Another comment! # This time two lines. class Foo: """Docstring for class Foo. Example from Sphinx docs.""" #: Doc comment for class attribute Foo.bar. #: It can have multiple lines. bar = 1 flox = 1.5 #: Doc comment for Foo.flox. One line only. baz = 2 """Docstring for class attribute Foo.baz.""" def __init__(self): #: Doc comment for instance attribute qux. self.qux = 3 self.spam = 4 """Docstring for instance attribute spam.""" #' <h1>This is pweave!</h1> @fast(really=True) async def wat(): # This comment, for some reason \ # contains a trailing backslash. async with X.open_async() as x: # Some more comments result = await x.method1() # Comment after ending a block. if result: print("A OK", file=sys.stdout) # Comment between things. print() # Some closing comments. # Maybe Vim or Emacs directives for formatting. # Who knows.
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/power_op_newline.py
tests/data/cases/power_op_newline.py
# flags: --line-length=0 importA;()<<0**0# # output importA ( () << 0 ** 0 ) #
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/module_docstring_2.py
tests/data/cases/module_docstring_2.py
"""I am a very helpful module docstring. With trailing spaces: Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. """ a = 1 """Look at me I'm a docstring... ............................................................ ............................................................ ............................................................ ............................................................ ............................................................ ............................................................ ............................................................ ........................................................NOT! """ b = 2 # output """I am a very helpful module docstring. With trailing spaces: Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. """ a = 1 """Look at me I'm a docstring... ............................................................ ............................................................ ............................................................ ............................................................ ............................................................ ............................................................ ............................................................ ........................................................NOT! """ b = 2
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/comment_after_escaped_newline.py
tests/data/cases/comment_after_escaped_newline.py
def bob(): \ # pylint: disable=W9016 pass def bobtwo(): \ \ # some comment here pass # output def bob(): # pylint: disable=W9016 pass def bobtwo(): # some comment here pass
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/beginning_backslash.py
tests/data/cases/beginning_backslash.py
\ print("hello, world") # output print("hello, world")
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/percent_precedence.py
tests/data/cases/percent_precedence.py
("" % a) ** 2 ("" % a)[0] ("" % a)() ("" % a).b 2 * ("" % a) 2 @ ("" % a) 2 / ("" % a) 2 // ("" % a) 2 % ("" % a) +("" % a) b + ("" % a) -("" % a) b - ("" % a) b + -("" % a) ~("" % a) 2 ** ("" % a) await ("" % a) b[("" % a)] b(("" % a)) # output ("" % a) ** 2 ("" % a)[0] ("" % a)() ("" % a).b 2 * ("" % a) 2 @ ("" % a) 2 / ("" % a) 2 // ("" % a) 2 % ("" % a) +("" % a) b + ("" % a) -("" % a) b - ("" % a) b + -("" % a) ~("" % a) 2 ** ("" % a) await ("" % a) b[("" % a)] b(("" % a))
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/preview_multiline_strings.py
tests/data/cases/preview_multiline_strings.py
# flags: --preview """cow say""", call(3, "dogsay", textwrap.dedent("""dove coo""" % "cowabunga")) call(3, "dogsay", textwrap.dedent("""dove coo""" % "cowabunga")) call(3, textwrap.dedent("""cow moo""" % "cowabunga"), "dogsay") call(3, "dogsay", textwrap.dedent("""crow caw""" % "cowabunga"),) call(3, textwrap.dedent("""cat meow""" % "cowabunga"), {"dog", "say"}) call(3, {"dog", "say"}, textwrap.dedent("""horse neigh""" % "cowabunga")) call(3, {"dog", "say"}, textwrap.dedent("""pig oink""" % "cowabunga"),) textwrap.dedent("""A one-line triple-quoted string.""") textwrap.dedent("""A two-line triple-quoted string since it goes to the next line.""") textwrap.dedent("""A three-line triple-quoted string that not only goes to the next line but also goes one line beyond.""") textwrap.dedent("""\ A triple-quoted string actually leveraging the textwrap.dedent functionality that ends in a trailing newline, representing e.g. file contents. """) path.write_text(textwrap.dedent("""\ A triple-quoted string actually leveraging the textwrap.dedent functionality that ends in a trailing newline, representing e.g. file contents. """)) path.write_text(textwrap.dedent("""\ A triple-quoted string actually leveraging the textwrap.dedent functionality that ends in a trailing newline, representing e.g. {config_filename} file contents. """.format("config_filename", config_filename))) # Another use case data = yaml.load("""\ a: 1 b: 2 """) data = yaml.load("""\ a: 1 b: 2 """,) data = yaml.load( """\ a: 1 b: 2 """ ) MULTILINE = """ foo """.replace("\n", "") generated_readme = lambda project_name: """ {} <Add content here!> """.strip().format(project_name) parser.usage += """ Custom extra help summary. Extra test: - with - bullets """ def get_stuff(cr, value): # original cr.execute(""" SELECT whatever FROM some_table t WHERE id = %s """, [value]) return cr.fetchone() def get_stuff(cr, value): # preferred cr.execute( """ SELECT whatever FROM some_table t WHERE id = %s """, [value], ) return cr.fetchone() call(arg1, arg2, """ short """, arg3=True) test_vectors = [ "one-liner\n", "two\nliner\n", """expressed as a three line mulitline string""", ] _wat = re.compile( r""" regex """, re.MULTILINE | re.VERBOSE, ) dis_c_instance_method = """\ %3d 0 LOAD_FAST 1 (x) 2 LOAD_CONST 1 (1) 4 COMPARE_OP 2 (==) 6 LOAD_FAST 0 (self) 8 STORE_ATTR 0 (x) 10 LOAD_CONST 0 (None) 12 RETURN_VALUE """ % (_C.__init__.__code__.co_firstlineno + 1,) path.write_text(textwrap.dedent("""\ A triple-quoted string actually {verb} the textwrap.dedent functionality that ends in a trailing newline, representing e.g. {file_type} file contents. """.format(verb="using", file_type="test"))) {"""cow moos"""} ["""cow moos"""] ["""cow moos""", """dog woofs and barks"""] def dastardly_default_value( cow: String = json.loads("""this is quite the dastadardly value!"""), **kwargs, ): pass print(f""" This {animal} moos and barks {animal} say """) msg = f"""The arguments {bad_arguments} were passed in. Please use `--build-option` instead, `--global-option` is reserved to flags like `--verbose` or `--quiet`. """ assert some_var == expected_result, """ test """ assert some_var == expected_result, f""" expected: {expected_result} actual: {some_var}""" def foo(): a = { xxxx_xxxxxxx.xxxxxx_xxxxxxxxxxxx_xxxxxx_xx_xxx_xxxxxx: { "xxxxx": """Sxxxxx xxxxxxxxxxxx xxx xxxxx (xxxxxx xxx xxxxxxx)""", "xxxxxxxx": ( """Sxxxxxxx xxxxxxxx, xxxxxxx xx xxxxxxxxx xxxxxxxxxxxxx xxxxxxx xxxxxxxxx xxx-xxxxxxxxxx xxxxxx xx xxx-xxxxxx""" ), "xxxxxxxx": """Sxxxxxxx xxxxxxxx, xxxxxxx xx xxxxxxxxx xxxxxxxxxxxxx xxxxxxx xxxxxxxxx xxx-xxxxxxxxxx xxxxxx xx xxx-xxxxxx""" }, } xxxx_xxxxxxx.xxxxxx_xxxxxxxxxxxx_xxxxxx_xx_xxx_xxxxxx = { "xxxxx": """Sxxxxx xxxxxxxxxxxx xxx xxxxx (xxxxxx xxx xxxxxxx)""", "xxxxxxxx": ( """Sxxxxxxx xxxxxxxx, xxxxxxx xx xxxxxxxxx xxxxxxxxxxxxx xxxxxxx xxxxxxxxx xxx-xxxxxxxxxx xxxxxx xx xxx-xxxxxx""" ), "xxxxx_xxxxxxxxxx_xxxxxxxxx_xx": ( """ a a a a a""" ), "xx_xxxxx_xxxxxxxxxx_xxxxxxxxx_xx": """ a a a a a""", } a = """ """ if """ """ == """ """ else """ """ a = """ """ if b else """ """ a = """ """ if """ """ == """ """ else b a = b if """ """ == """ """ else """ """ a = """ """ if b else c a = c if b else """ """ a = b if """ """ == """ """ else c # output """cow say""", call( 3, "dogsay", textwrap.dedent("""dove coo""" % "cowabunga"), ) call( 3, "dogsay", textwrap.dedent("""dove coo""" % "cowabunga"), ) call( 3, textwrap.dedent("""cow moo""" % "cowabunga"), "dogsay", ) call( 3, "dogsay", textwrap.dedent("""crow caw""" % "cowabunga"), ) call( 3, textwrap.dedent("""cat meow""" % "cowabunga"), {"dog", "say"}, ) call( 3, {"dog", "say"}, textwrap.dedent("""horse neigh""" % "cowabunga"), ) call( 3, {"dog", "say"}, textwrap.dedent("""pig oink""" % "cowabunga"), ) textwrap.dedent("""A one-line triple-quoted string.""") textwrap.dedent("""A two-line triple-quoted string since it goes to the next line.""") textwrap.dedent("""A three-line triple-quoted string that not only goes to the next line but also goes one line beyond.""") textwrap.dedent("""\ A triple-quoted string actually leveraging the textwrap.dedent functionality that ends in a trailing newline, representing e.g. file contents. """) path.write_text(textwrap.dedent("""\ A triple-quoted string actually leveraging the textwrap.dedent functionality that ends in a trailing newline, representing e.g. file contents. """)) path.write_text(textwrap.dedent("""\ A triple-quoted string actually leveraging the textwrap.dedent functionality that ends in a trailing newline, representing e.g. {config_filename} file contents. """.format("config_filename", config_filename))) # Another use case data = yaml.load("""\ a: 1 b: 2 """) data = yaml.load( """\ a: 1 b: 2 """, ) data = yaml.load("""\ a: 1 b: 2 """) MULTILINE = """ foo """.replace("\n", "") generated_readme = lambda project_name: """ {} <Add content here!> """.strip().format(project_name) parser.usage += """ Custom extra help summary. Extra test: - with - bullets """ def get_stuff(cr, value): # original cr.execute( """ SELECT whatever FROM some_table t WHERE id = %s """, [value], ) return cr.fetchone() def get_stuff(cr, value): # preferred cr.execute( """ SELECT whatever FROM some_table t WHERE id = %s """, [value], ) return cr.fetchone() call( arg1, arg2, """ short """, arg3=True, ) test_vectors = [ "one-liner\n", "two\nliner\n", """expressed as a three line mulitline string""", ] _wat = re.compile( r""" regex """, re.MULTILINE | re.VERBOSE, ) dis_c_instance_method = """\ %3d 0 LOAD_FAST 1 (x) 2 LOAD_CONST 1 (1) 4 COMPARE_OP 2 (==) 6 LOAD_FAST 0 (self) 8 STORE_ATTR 0 (x) 10 LOAD_CONST 0 (None) 12 RETURN_VALUE """ % (_C.__init__.__code__.co_firstlineno + 1,) path.write_text(textwrap.dedent("""\ A triple-quoted string actually {verb} the textwrap.dedent functionality that ends in a trailing newline, representing e.g. {file_type} file contents. """.format(verb="using", file_type="test"))) {"""cow moos"""} ["""cow moos"""] [ """cow moos""", """dog woofs and barks""", ] def dastardly_default_value( cow: String = json.loads("""this is quite the dastadardly value!"""), **kwargs, ): pass print(f""" This {animal} moos and barks {animal} say """) msg = f"""The arguments {bad_arguments} were passed in. Please use `--build-option` instead, `--global-option` is reserved to flags like `--verbose` or `--quiet`. """ assert some_var == expected_result, """ test """ assert some_var == expected_result, f""" expected: {expected_result} actual: {some_var}""" def foo(): a = { xxxx_xxxxxxx.xxxxxx_xxxxxxxxxxxx_xxxxxx_xx_xxx_xxxxxx: { "xxxxx": """Sxxxxx xxxxxxxxxxxx xxx xxxxx (xxxxxx xxx xxxxxxx)""", "xxxxxxxx": ( """Sxxxxxxx xxxxxxxx, xxxxxxx xx xxxxxxxxx xxxxxxxxxxxxx xxxxxxx xxxxxxxxx xxx-xxxxxxxxxx xxxxxx xx xxx-xxxxxx""" ), "xxxxxxxx": ( """Sxxxxxxx xxxxxxxx, xxxxxxx xx xxxxxxxxx xxxxxxxxxxxxx xxxxxxx xxxxxxxxx xxx-xxxxxxxxxx xxxxxx xx xxx-xxxxxx""" ), }, } xxxx_xxxxxxx.xxxxxx_xxxxxxxxxxxx_xxxxxx_xx_xxx_xxxxxx = { "xxxxx": """Sxxxxx xxxxxxxxxxxx xxx xxxxx (xxxxxx xxx xxxxxxx)""", "xxxxxxxx": ( """Sxxxxxxx xxxxxxxx, xxxxxxx xx xxxxxxxxx xxxxxxxxxxxxx xxxxxxx xxxxxxxxx xxx-xxxxxxxxxx xxxxxx xx xxx-xxxxxx""" ), "xxxxx_xxxxxxxxxx_xxxxxxxxx_xx": ( """ a a a a a""" ), "xx_xxxxx_xxxxxxxxxx_xxxxxxxxx_xx": ( """ a a a a a""" ), } a = ( """ """ if """ """ == """ """ else """ """ ) a = ( """ """ if b else """ """ ) a = ( """ """ if """ """ == """ """ else b ) a = ( b if """ """ == """ """ else """ """ ) a = ( """ """ if b else c ) a = ( c if b else """ """ ) a = ( b if """ """ == """ """ else c )
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/split_delimiter_comments.py
tests/data/cases/split_delimiter_comments.py
a = ( 1 + # type: ignore 2 # type: ignore ) a = ( 1 # type: ignore + 2 # type: ignore ) bad_split3 = ( "What if we have inline comments on " # First Comment "each line of a bad split? In that " # Second Comment "case, we should just leave it alone." # Third Comment ) parametrize( ( {}, {}, ), ( # foobar {}, {}, ), ) # output a = ( 1 # type: ignore + 2 # type: ignore ) a = ( 1 # type: ignore + 2 # type: ignore ) bad_split3 = ( "What if we have inline comments on " # First Comment "each line of a bad split? In that " # Second Comment "case, we should just leave it alone." # Third Comment ) parametrize( ( {}, {}, ), ( # foobar {}, {}, ), )
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/preview_fmtpass_imports.py
tests/data/cases/preview_fmtpass_imports.py
# flags: --preview # Regression test for https://github.com/psf/black/issues/3438 import ast import collections # fmt: skip import dataclasses # fmt: off import os # fmt: on import pathlib import re # fmt: skip import secrets # fmt: off import sys # fmt: on import tempfile import zoneinfo
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/starred_for_target.py
tests/data/cases/starred_for_target.py
# flags: --minimum-version=3.10 for x in *a, *b: print(x) for x in a, b, *c: print(x) for x in *a, b, c: print(x) for x in *a, b, *c: print(x) async for x in *a, *b: print(x) async for x in *a, b, *c: print(x) async for x in a, b, *c: print(x) async for x in ( *loooooooooooooooooooooong, very, *loooooooooooooooooooooooooooooooooooooooooooooooong, ): print(x)
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/type_params.py
tests/data/cases/type_params.py
# flags: --minimum-version=3.12 def func [T ](): pass async def func [ T ] (): pass class C[ T ] : pass def all_in[T : int,U : (bytes, str),* Ts,**P](): pass def really_long[WhatIsTheLongestTypeVarNameYouCanThinkOfEnoughToMakeBlackSplitThisLine](): pass def even_longer[WhatIsTheLongestTypeVarNameYouCanThinkOfEnoughToMakeBlackSplitThisLine: WhatIfItHadABound](): pass def it_gets_worse[WhatIsTheLongestTypeVarNameYouCanThinkOfEnoughToMakeBlackSplitThisLine, ItCouldBeGenericOverMultipleTypeVars](): pass def magic[Trailing, Comma,](): pass def weird_syntax[T: lambda: 42, U: a or b](): pass def name_3[name_0: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa if aaaaaaaaaaa else name_3](): pass # output def func[T](): pass async def func[T](): pass class C[T]: pass def all_in[T: int, U: (bytes, str), *Ts, **P](): pass def really_long[ WhatIsTheLongestTypeVarNameYouCanThinkOfEnoughToMakeBlackSplitThisLine ](): pass def even_longer[ WhatIsTheLongestTypeVarNameYouCanThinkOfEnoughToMakeBlackSplitThisLine: WhatIfItHadABound ](): pass def it_gets_worse[ WhatIsTheLongestTypeVarNameYouCanThinkOfEnoughToMakeBlackSplitThisLine, ItCouldBeGenericOverMultipleTypeVars, ](): pass def magic[ Trailing, Comma, ](): pass def weird_syntax[T: lambda: 42, U: a or b](): pass def name_3[ name_0: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa if aaaaaaaaaaa else name_3 ](): pass
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/remove_for_brackets.py
tests/data/cases/remove_for_brackets.py
# Only remove tuple brackets after `for` for (k, v) in d.items(): print(k, v) # Don't touch tuple brackets after `in` for module in (core, _unicodefun): if hasattr(module, "_verify_python3_env"): module._verify_python3_env = lambda: None # Brackets remain for long for loop lines for (why_would_anyone_choose_to_name_a_loop_variable_with_a_name_this_long, i_dont_know_but_we_should_still_check_the_behaviour_if_they_do) in d.items(): print(k, v) for (k, v) in dfkasdjfldsjflkdsjflkdsjfdslkfjldsjfgkjdshgkljjdsfldgkhsdofudsfudsofajdslkfjdslkfjldisfjdffjsdlkfjdlkjjkdflskadjldkfjsalkfjdasj.items(): print(k, v) # Test deeply nested brackets for (((((k, v))))) in d.items(): print(k, v) # output # Only remove tuple brackets after `for` for k, v in d.items(): print(k, v) # Don't touch tuple brackets after `in` for module in (core, _unicodefun): if hasattr(module, "_verify_python3_env"): module._verify_python3_env = lambda: None # Brackets remain for long for loop lines for ( why_would_anyone_choose_to_name_a_loop_variable_with_a_name_this_long, i_dont_know_but_we_should_still_check_the_behaviour_if_they_do, ) in d.items(): print(k, v) for ( k, v, ) in ( dfkasdjfldsjflkdsjflkdsjfdslkfjldsjfgkjdshgkljjdsfldgkhsdofudsfudsofajdslkfjdslkfjldisfjdffjsdlkfjdlkjjkdflskadjldkfjsalkfjdasj.items() ): print(k, v) # Test deeply nested brackets for k, v in d.items(): print(k, v)
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/docstring_preview.py
tests/data/cases/docstring_preview.py
def docstring_almost_at_line_limit(): """long docstring................................................................. """ def docstring_almost_at_line_limit_with_prefix(): f"""long docstring................................................................ """ def mulitline_docstring_almost_at_line_limit(): """long docstring................................................................. .................................................................................. """ def mulitline_docstring_almost_at_line_limit_with_prefix(): f"""long docstring................................................................ .................................................................................. """ def docstring_at_line_limit(): """long docstring................................................................""" def docstring_at_line_limit_with_prefix(): f"""long docstring...............................................................""" def multiline_docstring_at_line_limit(): """first line----------------------------------------------------------------------- second line----------------------------------------------------------------------""" def multiline_docstring_at_line_limit_with_prefix(): f"""first line---------------------------------------------------------------------- second line----------------------------------------------------------------------""" def single_quote_docstring_over_line_limit(): "We do not want to put the closing quote on a new line as that is invalid (see GH-3141)." def single_quote_docstring_over_line_limit2(): 'We do not want to put the closing quote on a new line as that is invalid (see GH-3141).' # output def docstring_almost_at_line_limit(): """long docstring.................................................................""" def docstring_almost_at_line_limit_with_prefix(): f"""long docstring................................................................ """ def mulitline_docstring_almost_at_line_limit(): """long docstring................................................................. .................................................................................. """ def mulitline_docstring_almost_at_line_limit_with_prefix(): f"""long docstring................................................................ .................................................................................. """ def docstring_at_line_limit(): """long docstring................................................................""" def docstring_at_line_limit_with_prefix(): f"""long docstring...............................................................""" def multiline_docstring_at_line_limit(): """first line----------------------------------------------------------------------- second line----------------------------------------------------------------------""" def multiline_docstring_at_line_limit_with_prefix(): f"""first line---------------------------------------------------------------------- second line----------------------------------------------------------------------""" def single_quote_docstring_over_line_limit(): "We do not want to put the closing quote on a new line as that is invalid (see GH-3141)." def single_quote_docstring_over_line_limit2(): "We do not want to put the closing quote on a new line as that is invalid (see GH-3141)."
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/pep604_union_types_line_breaks.py
tests/data/cases/pep604_union_types_line_breaks.py
# flags: --minimum-version=3.10 # This has always worked z= Loooooooooooooooooooooooong | Loooooooooooooooooooooooong | Loooooooooooooooooooooooong | Loooooooooooooooooooooooong # "AnnAssign"s now also work z: Loooooooooooooooooooooooong | Loooooooooooooooooooooooong | Loooooooooooooooooooooooong | Loooooooooooooooooooooooong z: (Short | Short2 | Short3 | Short4) z: (int) z: ((int)) z: Loooooooooooooooooooooooong | Loooooooooooooooooooooooong | Loooooooooooooooooooooooong | Loooooooooooooooooooooooong = 7 z: (Short | Short2 | Short3 | Short4) = 8 z: (int) = 2.3 z: ((int)) = foo() # In case I go for not enforcing parantheses, this might get improved at the same time x = ( z == 9999999999999999999999999999999999999999 | 9999999999999999999999999999999999999999 | 9999999999999999999999999999999999999999 | 9999999999999999999999999999999999999999, y == 9999999999999999999999999999999999999999 + 9999999999999999999999999999999999999999 + 9999999999999999999999999999999999999999 + 9999999999999999999999999999999999999999, ) x = ( z == (9999999999999999999999999999999999999999 | 9999999999999999999999999999999999999999 | 9999999999999999999999999999999999999999 | 9999999999999999999999999999999999999999), y == (9999999999999999999999999999999999999999 + 9999999999999999999999999999999999999999 + 9999999999999999999999999999999999999999 + 9999999999999999999999999999999999999999), ) # handle formatting of "tname"s in parameter list # remove unnecessary paren def foo(i: (int)) -> None: ... # this is a syntax error in the type annotation according to mypy, but it's not invalid *python* code, so make sure we don't mess with it and make it so. def foo(i: (int,)) -> None: ... def foo( i: int, x: Loooooooooooooooooooooooong | Looooooooooooooooong | Looooooooooooooooooooong | Looooooong, *, s: str, ) -> None: pass @app.get("/path/") async def foo( q: str | None = Query(None, title="Some long title", description="Some long description") ): pass def f( max_jobs: int | None = Option( None, help="Maximum number of jobs to launch. And some additional text." ), another_option: bool = False ): ... # output # This has always worked z = ( Loooooooooooooooooooooooong | Loooooooooooooooooooooooong | Loooooooooooooooooooooooong | Loooooooooooooooooooooooong ) # "AnnAssign"s now also work z: ( Loooooooooooooooooooooooong | Loooooooooooooooooooooooong | Loooooooooooooooooooooooong | Loooooooooooooooooooooooong ) z: Short | Short2 | Short3 | Short4 z: int z: int z: ( Loooooooooooooooooooooooong | Loooooooooooooooooooooooong | Loooooooooooooooooooooooong | Loooooooooooooooooooooooong ) = 7 z: Short | Short2 | Short3 | Short4 = 8 z: int = 2.3 z: int = foo() # In case I go for not enforcing parantheses, this might get improved at the same time x = ( z == 9999999999999999999999999999999999999999 | 9999999999999999999999999999999999999999 | 9999999999999999999999999999999999999999 | 9999999999999999999999999999999999999999, y == 9999999999999999999999999999999999999999 + 9999999999999999999999999999999999999999 + 9999999999999999999999999999999999999999 + 9999999999999999999999999999999999999999, ) x = ( z == ( 9999999999999999999999999999999999999999 | 9999999999999999999999999999999999999999 | 9999999999999999999999999999999999999999 | 9999999999999999999999999999999999999999 ), y == ( 9999999999999999999999999999999999999999 + 9999999999999999999999999999999999999999 + 9999999999999999999999999999999999999999 + 9999999999999999999999999999999999999999 ), ) # handle formatting of "tname"s in parameter list # remove unnecessary paren def foo(i: int) -> None: ... # this is a syntax error in the type annotation according to mypy, but it's not invalid *python* code, so make sure we don't mess with it and make it so. def foo(i: (int,)) -> None: ... def foo( i: int, x: ( Loooooooooooooooooooooooong | Looooooooooooooooong | Looooooooooooooooooooong | Looooooong ), *, s: str, ) -> None: pass @app.get("/path/") async def foo( q: str | None = Query( None, title="Some long title", description="Some long description" ) ): pass def f( max_jobs: int | None = Option( None, help="Maximum number of jobs to launch. And some additional text." ), another_option: bool = False, ): ...
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/python39.py
tests/data/cases/python39.py
@relaxed_decorator[0] def f(): ... @relaxed_decorator[extremely_long_name_that_definitely_will_not_fit_on_one_line_of_standard_length] def f(): ... @extremely_long_variable_name_that_doesnt_fit := complex.expression(with_long="arguments_value_that_wont_fit_at_the_end_of_the_line") def f(): ... # output @relaxed_decorator[0] def f(): ... @relaxed_decorator[ extremely_long_name_that_definitely_will_not_fit_on_one_line_of_standard_length ] def f(): ... @extremely_long_variable_name_that_doesnt_fit := complex.expression( with_long="arguments_value_that_wont_fit_at_the_end_of_the_line" ) def f(): ...
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/pep_572_py39.py
tests/data/cases/pep_572_py39.py
# Unparenthesized walruses are now allowed in set literals & set comprehensions # since Python 3.9 {x := 1, 2, 3} {x4 := x**5 for x in range(7)} # We better not remove the parentheses here (since it's a 3.10 feature) x[(a := 1)] x[(a := 1), (b := 3)]
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/pattern_matching_complex.py
tests/data/cases/pattern_matching_complex.py
# flags: --minimum-version=3.10 # Cases sampled from Lib/test/test_patma.py # case black_test_patma_098 match x: case -0j: y = 0 # case black_test_patma_142 match x: case bytes(z): y = 0 # case black_test_patma_073 match x: case 0 if 0: y = 0 case 0 if 1: y = 1 # case black_test_patma_006 match 3: case 0 | 1 | 2 | 3: x = True # case black_test_patma_049 match x: case [0, 1] | [1, 0]: y = 0 # case black_check_sequence_then_mapping match x: case [*_]: return "seq" case {}: return "map" # case black_test_patma_035 match x: case {0: [1, 2, {}]}: y = 0 case {0: [1, 2, {}] | True} | {1: [[]]} | {0: [1, 2, {}]} | [] | "X" | {}: y = 1 case []: y = 2 # case black_test_patma_107 match x: case 0.25 + 1.75j: y = 0 # case black_test_patma_097 match x: case -0j: y = 0 # case black_test_patma_007 match 4: case 0 | 1 | 2 | 3: x = True # case black_test_patma_154 match x: case 0 if x: y = 0 # case black_test_patma_134 match x: case {1: 0}: y = 0 case {0: 0}: y = 1 case {**z}: y = 2 # case black_test_patma_185 match Seq(): case [*_]: y = 0 # case black_test_patma_063 match x: case 1: y = 0 case 1: y = 1 # case black_test_patma_248 match x: case {"foo": bar}: y = bar # case black_test_patma_019 match (0, 1, 2): case [0, 1, *x, 2]: y = 0 # case black_test_patma_052 match x: case [0]: y = 0 case [1, 0] if x := x[:0]: y = 1 case [1, 0]: y = 2 # case black_test_patma_191 match w: case [x, y, *_]: z = 0 # case black_test_patma_110 match x: case -0.25 - 1.75j: y = 0 # case black_test_patma_151 match (x,): case [y]: z = 0 # case black_test_patma_114 match x: case A.B.C.D: y = 0 # case black_test_patma_232 match x: case None: y = 0 # case black_test_patma_058 match x: case 0: y = 0 # case black_test_patma_233 match x: case False: y = 0 # case black_test_patma_078 match x: case []: y = 0 case [""]: y = 1 case "": y = 2 # case black_test_patma_156 match x: case z: y = 0 # case black_test_patma_189 match w: case [x, y, *rest]: z = 0 # case black_test_patma_042 match x: case (0 as z) | (1 as z) | (2 as z) if z == x % 2: y = 0 # case black_test_patma_034 match x: case {0: [1, 2, {}]}: y = 0 case {0: [1, 2, {}] | False} | {1: [[]]} | {0: [1, 2, {}]} | [] | "X" | {}: y = 1 case []: y = 2 # issue 3790 match (X.type, Y): case _: pass # issue 3487 match = re.match(r"(?P<grade>LD|MD|HD)(?P<material>AL|SS)", "HDSS") match (match.group("grade"), match.group("material")): case ("MD" | "HD", "SS" as code): print("You will get here")
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/fmtskip13.py
tests/data/cases/fmtskip13.py
# flags: --preview t = ( {"foo": "very long string", "bar": "another very long string", "baz": "we should run out of space by now"}, # fmt: skip {"foo": "bar"}, ) t = ( { "foo": "very long string", "bar": "another very long string", "baz": "we should run out of space by now", }, # fmt: skip {"foo": "bar"}, ) t = ( {"foo": "very long string", "bar": "another very long string", "baz": "we should run out of space by now"}, # fmt: skip {"foo": "bar",}, ) t = ( { "foo": "very long string", "bar": "another very long string", "baz": "we should run out of space by now", }, # fmt: skip {"foo": "bar",}, ) # output t = ( {"foo": "very long string", "bar": "another very long string", "baz": "we should run out of space by now"}, # fmt: skip {"foo": "bar"}, ) t = ( { "foo": "very long string", "bar": "another very long string", "baz": "we should run out of space by now", }, # fmt: skip {"foo": "bar"}, ) t = ( {"foo": "very long string", "bar": "another very long string", "baz": "we should run out of space by now"}, # fmt: skip { "foo": "bar", }, ) t = ( { "foo": "very long string", "bar": "another very long string", "baz": "we should run out of space by now", }, # fmt: skip { "foo": "bar", }, )
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/class_blank_parentheses.py
tests/data/cases/class_blank_parentheses.py
class SimpleClassWithBlankParentheses(): pass class ClassWithSpaceParentheses ( ): first_test_data = 90 second_test_data = 100 def test_func(self): return None class ClassWithEmptyFunc(object): def func_with_blank_parentheses(): return 5 def public_func_with_blank_parentheses(): return None def class_under_the_func_with_blank_parentheses(): class InsideFunc(): pass class NormalClass ( ): def func_for_testing(self, first, second): sum = first + second return sum # output class SimpleClassWithBlankParentheses: pass class ClassWithSpaceParentheses: first_test_data = 90 second_test_data = 100 def test_func(self): return None class ClassWithEmptyFunc(object): def func_with_blank_parentheses(): return 5 def public_func_with_blank_parentheses(): return None def class_under_the_func_with_blank_parentheses(): class InsideFunc: pass class NormalClass: def func_for_testing(self, first, second): sum = first + second return sum
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/preview_return_annotation_brackets_string.py
tests/data/cases/preview_return_annotation_brackets_string.py
# flags: --unstable # Long string example def frobnicate() -> "ThisIsTrulyUnreasonablyExtremelyLongClassName | list[ThisIsTrulyUnreasonablyExtremelyLongClassName]": pass # splitting the string breaks if there's any parameters def frobnicate(a) -> "ThisIsTrulyUnreasonablyExtremelyLongClassName | list[ThisIsTrulyUnreasonablyExtremelyLongClassName]": pass # output # Long string example def frobnicate() -> ( "ThisIsTrulyUnreasonablyExtremelyLongClassName |" " list[ThisIsTrulyUnreasonablyExtremelyLongClassName]" ): pass # splitting the string breaks if there's any parameters def frobnicate( a, ) -> "ThisIsTrulyUnreasonablyExtremelyLongClassName | list[ThisIsTrulyUnreasonablyExtremelyLongClassName]": pass
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false