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/remove_newline_after_code_block_open.py | tests/data/cases/remove_newline_after_code_block_open.py | import random
def foo1():
print("The newline above me should be kept!")
def foo2():
print("All the newlines above me should be kept!")
def foo3():
print("No newline above me!")
print("There is a newline above me, and that's OK!")
def foo4():
# There is a comment here
print("The newline above me should not be deleted!")
class Foo:
def bar(self):
print("The newline above me should be kept!")
for i in range(5):
print(f"{i}) The line above me should be kept!")
for i in range(5):
print(f"{i}) The lines above me should be kept!")
for i in range(5):
for j in range(7):
print(f"{i}) The lines above me should be kept!")
if random.randint(0, 3) == 0:
print("The new line above me will be kept!")
if random.randint(0, 3) == 0:
print("The new lines above me will be kept!")
if random.randint(0, 3) == 0:
if random.uniform(0, 1) > 0.5:
print("Two lines above me will be kept!")
while True:
print("The newline above me should be kept!")
while True:
print("The newlines above me should be kept!")
while True:
while False:
print("The newlines above me should be kept!")
with open("/path/to/file.txt", mode="w") as file:
file.write("The new line above me will be kept!")
with open("/path/to/file.txt", mode="w") as file:
file.write("The new lines above me will be kept!")
with open("/path/to/file.txt", mode="r") as read_file:
with open("/path/to/output_file.txt", mode="w") as write_file:
write_file.writelines(read_file.readlines())
# output
import random
def foo1():
print("The newline above me should be kept!")
def foo2():
print("All the newlines above me should be kept!")
def foo3():
print("No newline above me!")
print("There is a newline above me, and that's OK!")
def foo4():
# There is a comment here
print("The newline above me should not be deleted!")
class Foo:
def bar(self):
print("The newline above me should be kept!")
for i in range(5):
print(f"{i}) The line above me should be kept!")
for i in range(5):
print(f"{i}) The lines above me should be kept!")
for i in range(5):
for j in range(7):
print(f"{i}) The lines above me should be kept!")
if random.randint(0, 3) == 0:
print("The new line above me will be kept!")
if random.randint(0, 3) == 0:
print("The new lines above me will be kept!")
if random.randint(0, 3) == 0:
if random.uniform(0, 1) > 0.5:
print("Two lines above me will be kept!")
while True:
print("The newline above me should be kept!")
while True:
print("The newlines above me should be kept!")
while True:
while False:
print("The newlines above me should be kept!")
with open("/path/to/file.txt", mode="w") as file:
file.write("The new line above me will be kept!")
with open("/path/to/file.txt", mode="w") as file:
file.write("The new lines above me will be kept!")
with open("/path/to/file.txt", mode="r") as read_file:
with open("/path/to/output_file.txt", mode="w") as write_file:
write_file.writelines(read_file.readlines())
| python | MIT | c3cc5a95d4f72e6ccc27ebae23344fce8cc70786 | 2026-01-04T14:40:23.735327Z | false |
psf/black | https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/pattern_matching_extras.py | tests/data/cases/pattern_matching_extras.py | # flags: --minimum-version=3.10
import match
match something:
case [a as b]:
print(b)
case [a as b, c, d, e as f]:
print(f)
case Point(a as b):
print(b)
case Point(int() as x, int() as y):
print(x, y)
match = 1
case: int = re.match(something)
match re.match(case):
case type("match", match):
pass
case match:
pass
def func(match: case, case: match) -> case:
match Something():
case func(match, case):
...
case another:
...
match a, *b, c:
case [*_]:
assert "seq" == _
case {}:
assert "map" == b
match match(
case,
match(
match, case, match, looooooooooooooooooooooooooooooooooooong, match, case, match
),
case,
):
case case(
match=case,
case=re.match(
loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong
),
):
pass
case [a as match]:
pass
case case:
pass
case something:
pass
match match:
case case:
pass
match a, *b(), c:
case d, *f, g:
pass
match something:
case {
"key": key as key_1,
"password": PASS.ONE | PASS.TWO | PASS.THREE as password,
}:
pass
case {"maybe": something(complicated as this) as that}:
pass
match something:
case 1 as a:
pass
case 2 as b, 3 as c:
pass
case 4 as d, (5 as e), (6 | 7 as g), *h:
pass
match bar1:
case Foo(aa=Callable() as aa, bb=int()):
print(bar1.aa, bar1.bb)
case _:
print("no match", "\n")
match bar1:
case Foo(
normal=x, perhaps=[list, {"x": d, "y": 1.0}] as y, otherwise=something, q=t as u
):
pass
| python | MIT | c3cc5a95d4f72e6ccc27ebae23344fce8cc70786 | 2026-01-04T14:40:23.735327Z | false |
psf/black | https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/no_blank_line_before_docstring.py | tests/data/cases/no_blank_line_before_docstring.py | def line_before_docstring():
"""Please move me up"""
class LineBeforeDocstring:
"""Please move me up"""
class EvenIfThereIsAMethodAfter:
"""I'm the docstring"""
def method(self):
pass
class TwoLinesBeforeDocstring:
"""I want to be treated the same as if I were closer"""
class MultilineDocstringsAsWell:
"""I'm so far
and on so many lines...
"""
class SingleQuotedDocstring:
"I'm a docstring but I don't even get triple quotes."
# output
def line_before_docstring():
"""Please move me up"""
class LineBeforeDocstring:
"""Please move me up"""
class EvenIfThereIsAMethodAfter:
"""I'm the docstring"""
def method(self):
pass
class TwoLinesBeforeDocstring:
"""I want to be treated the same as if I were closer"""
class MultilineDocstringsAsWell:
"""I'm so far
and on so many lines...
"""
class SingleQuotedDocstring:
"I'm a docstring but I don't even get triple quotes."
| python | MIT | c3cc5a95d4f72e6ccc27ebae23344fce8cc70786 | 2026-01-04T14:40:23.735327Z | false |
psf/black | https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/comments5.py | tests/data/cases/comments5.py | while True:
if something.changed:
do.stuff() # trailing comment
# Comment belongs to the `if` block.
# This one belongs to the `while` block.
# Should this one, too? I guess so.
# This one is properly standalone now.
for i in range(100):
# first we do this
if i % 33 == 0:
break
# then we do this
print(i)
# and finally we loop around
with open(some_temp_file) as f:
data = f.read()
try:
with open(some_other_file) as w:
w.write(data)
except OSError:
print("problems")
import sys
# leading function comment
def wat():
...
# trailing function comment
# SECTION COMMENT
# leading 1
@deco1
# leading 2
@deco2(with_args=True)
# leading 3
@deco3
def decorated1(): ...
# leading 1
@deco1
# leading 2
@deco2(with_args=True)
# leading function comment
def decorated1(): ...
# Note: this is fixed in
# Preview.empty_lines_before_class_or_def_with_leading_comments.
# In the current style, the user will have to split those lines by hand.
some_instruction
# This comment should be split from `some_instruction` by two lines but isn't.
def g(): ...
if __name__ == "__main__":
main()
| python | MIT | c3cc5a95d4f72e6ccc27ebae23344fce8cc70786 | 2026-01-04T14:40:23.735327Z | false |
psf/black | https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/fmtskip2.py | tests/data/cases/fmtskip2.py | # flags: --no-preview-line-length-1
# l2 loses the comment with line-length=1 in preview mode
l1 = ["This list should be broken up", "into multiple lines", "because it is way too long"]
l2 = ["But this list shouldn't", "even though it also has", "way too many characters in it"] # fmt: skip
l3 = ["I have", "trailing comma", "so I should be braked",]
# output
# l2 loses the comment with line-length=1 in preview mode
l1 = [
"This list should be broken up",
"into multiple lines",
"because it is way too long",
]
l2 = ["But this list shouldn't", "even though it also has", "way too many characters in it"] # fmt: skip
l3 = [
"I have",
"trailing comma",
"so I should be braked",
]
| python | MIT | c3cc5a95d4f72e6ccc27ebae23344fce8cc70786 | 2026-01-04T14:40:23.735327Z | false |
psf/black | https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/pep_604.py | tests/data/cases/pep_604.py | def some_very_long_name_function() -> my_module.Asdf | my_module.AnotherType | my_module.YetAnotherType | None:
pass
def some_very_long_name_function() -> my_module.Asdf | my_module.AnotherType | my_module.YetAnotherType | my_module.EvenMoreType | None:
pass
# output
def some_very_long_name_function() -> (
my_module.Asdf | my_module.AnotherType | my_module.YetAnotherType | None
):
pass
def some_very_long_name_function() -> (
my_module.Asdf
| my_module.AnotherType
| my_module.YetAnotherType
| my_module.EvenMoreType
| None
):
pass
| python | MIT | c3cc5a95d4f72e6ccc27ebae23344fce8cc70786 | 2026-01-04T14:40:23.735327Z | false |
psf/black | https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/fmtskip11.py | tests/data/cases/fmtskip11.py | def foo():
pass
# comment 1 # fmt: skip
# comment 2
[
(1, 2),
# # fmt: off
# (3,
# 4),
# # fmt: on
(5, 6),
]
[
(1, 2),
# # fmt: off
# (3,
# 4),
# fmt: on
(5, 6),
]
[
(1, 2),
# fmt: off
# (3,
# 4),
# # fmt: on
(5, 6),
]
[
(1, 2),
# fmt: off
# (3,
# 4),
# fmt: on
(5, 6),
]
[
(1, 2),
# # fmt: off
(3,
4),
# # fmt: on
(5, 6),
]
[
(1, 2),
# # fmt: off
(3,
4),
# fmt: on
(5, 6),
]
[
(1, 2),
# fmt: off
(3,
4),
# # fmt: on
(5, 6),
]
[
(1, 2),
# fmt: off
(3,
4),
# fmt: on
(5, 6),
]
if False:
# fmt: off # some other comment
pass
| python | MIT | c3cc5a95d4f72e6ccc27ebae23344fce8cc70786 | 2026-01-04T14:40:23.735327Z | false |
psf/black | https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/line_ranges_decorator_edge_case.py | tests/data/cases/line_ranges_decorator_edge_case.py | # flags: --line-ranges=6-7
class Foo:
@overload
def foo(): ...
def fox(self):
print()
| python | MIT | c3cc5a95d4f72e6ccc27ebae23344fce8cc70786 | 2026-01-04T14:40:23.735327Z | false |
psf/black | https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/nested_stub.py | tests/data/cases/nested_stub.py | # flags: --pyi
import sys
class Outer:
class InnerStub: ...
outer_attr_after_inner_stub: int
class Inner:
inner_attr: int
outer_attr: int
if sys.version_info > (3, 7):
if sys.platform == "win32":
assignment = 1
def function_definition(self): ...
def f1(self) -> str: ...
if sys.platform != "win32":
def function_definition(self): ...
assignment = 1
def f2(self) -> str: ...
class TopLevel:
class Nested1:
foo: int
def bar(self): ...
field = 1
class Nested2:
def bar(self): ...
foo: int
field = 1
# output
import sys
class Outer:
class InnerStub: ...
outer_attr_after_inner_stub: int
class Inner:
inner_attr: int
outer_attr: int
if sys.version_info > (3, 7):
if sys.platform == "win32":
assignment = 1
def function_definition(self): ...
def f1(self) -> str: ...
if sys.platform != "win32":
def function_definition(self): ...
assignment = 1
def f2(self) -> str: ...
class TopLevel:
class Nested1:
foo: int
def bar(self): ...
field = 1
class Nested2:
def bar(self): ...
foo: int
field = 1
| python | MIT | c3cc5a95d4f72e6ccc27ebae23344fce8cc70786 | 2026-01-04T14:40:23.735327Z | false |
psf/black | https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/pep_570.py | tests/data/cases/pep_570.py | def positional_only_arg(a, /):
pass
def all_markers(a, b, /, c, d, *, e, f):
pass
def all_markers_with_args_and_kwargs(
a_long_one,
b_long_one,
/,
c_long_one,
d_long_one,
*args,
e_long_one,
f_long_one,
**kwargs,
):
pass
def all_markers_with_defaults(a, b=1, /, c=2, d=3, *, e=4, f=5):
pass
def long_one_with_long_parameter_names(
but_all_of_them,
are_positional_only,
arguments_mmmmkay,
so_this_is_only_valid_after,
three_point_eight,
/,
):
pass
lambda a, /: a
lambda a, b, /, c, d, *, e, f: a
lambda a, b, /, c, d, *args, e, f, **kwargs: args
lambda a, b=1, /, c=2, d=3, *, e=4, f=5: 1
| python | MIT | c3cc5a95d4f72e6ccc27ebae23344fce8cc70786 | 2026-01-04T14:40:23.735327Z | false |
psf/black | https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/fmtonoff3.py | tests/data/cases/fmtonoff3.py | # fmt: off
x = [
1, 2,
3, 4,
]
# fmt: on
# fmt: off
x = [
1, 2,
3, 4,
]
# fmt: on
x = [
1, 2, 3, 4
]
# output
# fmt: off
x = [
1, 2,
3, 4,
]
# fmt: on
# fmt: off
x = [
1, 2,
3, 4,
]
# fmt: on
x = [1, 2, 3, 4]
| python | MIT | c3cc5a95d4f72e6ccc27ebae23344fce8cc70786 | 2026-01-04T14:40:23.735327Z | false |
psf/black | https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/pep_572_py310.py | tests/data/cases/pep_572_py310.py | # flags: --minimum-version=3.10
# Unparenthesized walruses are now allowed in indices since Python 3.10.
x[a := 0]
x[a := 0, b := 1]
x[5, b := 0]
# Walruses are allowed inside generator expressions on function calls since 3.10.
if any(match := pattern_error.match(s) for s in buffer):
if match.group(2) == data_not_available:
# Error OK to ignore.
pass
f(a := b + c for c in range(10))
f((a := b + c for c in range(10)), x)
f(y=(a := b + c for c in range(10)))
f(x, (a := b + c for c in range(10)), y=z, **q)
# Don't remove parens when assignment expr is one of the exprs in a with statement
with x, (a := b):
pass
| python | MIT | c3cc5a95d4f72e6ccc27ebae23344fce8cc70786 | 2026-01-04T14:40:23.735327Z | false |
psf/black | https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/tupleassign.py | tests/data/cases/tupleassign.py | # This is a standalone comment.
sdfjklsdfsjldkflkjsf, sdfjsdfjlksdljkfsdlkf, sdfsdjfklsdfjlksdljkf, sdsfsdfjskdflsfsdf = 1, 2, 3
# This is as well.
this_will_be_wrapped_in_parens, = struct.unpack(b"12345678901234567890")
(a,) = call()
# output
# This is a standalone comment.
(
sdfjklsdfsjldkflkjsf,
sdfjsdfjlksdljkfsdlkf,
sdfsdjfklsdfjlksdljkf,
sdsfsdfjskdflsfsdf,
) = (1, 2, 3)
# This is as well.
(this_will_be_wrapped_in_parens,) = struct.unpack(b"12345678901234567890")
(a,) = call() | python | MIT | c3cc5a95d4f72e6ccc27ebae23344fce8cc70786 | 2026-01-04T14:40:23.735327Z | false |
psf/black | https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/one_element_subscript.py | tests/data/cases/one_element_subscript.py | # We should not treat the trailing comma
# in a single-element subscript.
a: tuple[int,]
b = tuple[int,]
# The magic comma still applies to multi-element subscripts.
c: tuple[int, int,]
d = tuple[int, int,]
# Magic commas still work as expected for non-subscripts.
small_list = [1,]
list_of_types = [tuple[int,],]
# output
# We should not treat the trailing comma
# in a single-element subscript.
a: tuple[int,]
b = tuple[int,]
# The magic comma still applies to multi-element subscripts.
c: tuple[
int,
int,
]
d = tuple[
int,
int,
]
# Magic commas still work as expected for non-subscripts.
small_list = [
1,
]
list_of_types = [
tuple[int,],
]
| python | MIT | c3cc5a95d4f72e6ccc27ebae23344fce8cc70786 | 2026-01-04T14:40:23.735327Z | false |
psf/black | https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/fmtpass_imports.py | tests/data/cases/fmtpass_imports.py | # 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/class_methods_new_line.py | tests/data/cases/class_methods_new_line.py | class ClassSimplest:
pass
class ClassWithSingleField:
a = 1
class ClassWithJustTheDocstring:
"""Just a docstring."""
class ClassWithInit:
def __init__(self):
pass
class ClassWithTheDocstringAndInit:
"""Just a docstring."""
def __init__(self):
pass
class ClassWithInitAndVars:
cls_var = 100
def __init__(self):
pass
class ClassWithInitAndVarsAndDocstring:
"""Test class"""
cls_var = 100
def __init__(self):
pass
class ClassWithDecoInit:
@deco
def __init__(self):
pass
class ClassWithDecoInitAndVars:
cls_var = 100
@deco
def __init__(self):
pass
class ClassWithDecoInitAndVarsAndDocstring:
"""Test class"""
cls_var = 100
@deco
def __init__(self):
pass
class ClassSimplestWithInner:
class Inner:
pass
class ClassSimplestWithInnerWithDocstring:
class Inner:
"""Just a docstring."""
def __init__(self):
pass
class ClassWithSingleFieldWithInner:
a = 1
class Inner:
pass
class ClassWithJustTheDocstringWithInner:
"""Just a docstring."""
class Inner:
pass
class ClassWithInitWithInner:
class Inner:
pass
def __init__(self):
pass
class ClassWithInitAndVarsWithInner:
cls_var = 100
class Inner:
pass
def __init__(self):
pass
class ClassWithInitAndVarsAndDocstringWithInner:
"""Test class"""
cls_var = 100
class Inner:
pass
def __init__(self):
pass
class ClassWithDecoInitWithInner:
class Inner:
pass
@deco
def __init__(self):
pass
class ClassWithDecoInitAndVarsWithInner:
cls_var = 100
class Inner:
pass
@deco
def __init__(self):
pass
class ClassWithDecoInitAndVarsAndDocstringWithInner:
"""Test class"""
cls_var = 100
class Inner:
pass
@deco
def __init__(self):
pass
class ClassWithDecoInitAndVarsAndDocstringWithInner2:
"""Test class"""
class Inner:
pass
cls_var = 100
@deco
def __init__(self):
pass
# output
class ClassSimplest:
pass
class ClassWithSingleField:
a = 1
class ClassWithJustTheDocstring:
"""Just a docstring."""
class ClassWithInit:
def __init__(self):
pass
class ClassWithTheDocstringAndInit:
"""Just a docstring."""
def __init__(self):
pass
class ClassWithInitAndVars:
cls_var = 100
def __init__(self):
pass
class ClassWithInitAndVarsAndDocstring:
"""Test class"""
cls_var = 100
def __init__(self):
pass
class ClassWithDecoInit:
@deco
def __init__(self):
pass
class ClassWithDecoInitAndVars:
cls_var = 100
@deco
def __init__(self):
pass
class ClassWithDecoInitAndVarsAndDocstring:
"""Test class"""
cls_var = 100
@deco
def __init__(self):
pass
class ClassSimplestWithInner:
class Inner:
pass
class ClassSimplestWithInnerWithDocstring:
class Inner:
"""Just a docstring."""
def __init__(self):
pass
class ClassWithSingleFieldWithInner:
a = 1
class Inner:
pass
class ClassWithJustTheDocstringWithInner:
"""Just a docstring."""
class Inner:
pass
class ClassWithInitWithInner:
class Inner:
pass
def __init__(self):
pass
class ClassWithInitAndVarsWithInner:
cls_var = 100
class Inner:
pass
def __init__(self):
pass
class ClassWithInitAndVarsAndDocstringWithInner:
"""Test class"""
cls_var = 100
class Inner:
pass
def __init__(self):
pass
class ClassWithDecoInitWithInner:
class Inner:
pass
@deco
def __init__(self):
pass
class ClassWithDecoInitAndVarsWithInner:
cls_var = 100
class Inner:
pass
@deco
def __init__(self):
pass
class ClassWithDecoInitAndVarsAndDocstringWithInner:
"""Test class"""
cls_var = 100
class Inner:
pass
@deco
def __init__(self):
pass
class ClassWithDecoInitAndVarsAndDocstringWithInner2:
"""Test class"""
class Inner:
pass
cls_var = 100
@deco
def __init__(self):
pass
| python | MIT | c3cc5a95d4f72e6ccc27ebae23344fce8cc70786 | 2026-01-04T14:40:23.735327Z | false |
psf/black | https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/docstring_no_string_normalization.py | tests/data/cases/docstring_no_string_normalization.py | # flags: --skip-string-normalization
class ALonelyClass:
'''
A multiline class docstring.
'''
def AnEquallyLonelyMethod(self):
'''
A multiline method docstring'''
pass
def one_function():
'''This is a docstring with a single line of text.'''
pass
def shockingly_the_quotes_are_normalized():
'''This is a multiline docstring.
This is a multiline docstring.
This is a multiline docstring.
'''
pass
def foo():
"""This is a docstring with
some lines of text here
"""
return
def baz():
'''"This" is a string with some
embedded "quotes"'''
return
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 believe_it_or_not_this_is_in_the_py_stdlib(): '''
"hey yah"'''
def shockingly_the_quotes_are_normalized_v2():
'''
Docstring Docstring Docstring
'''
pass
def backslash_space():
'\ '
def multiline_backslash_1():
'''
hey\there\
\ '''
def multiline_backslash_2():
'''
hey there \ '''
def multiline_backslash_3():
'''
already escaped \\ '''
# output
class ALonelyClass:
'''
A multiline class docstring.
'''
def AnEquallyLonelyMethod(self):
'''
A multiline method docstring'''
pass
def one_function():
'''This is a docstring with a single line of text.'''
pass
def shockingly_the_quotes_are_normalized():
'''This is a multiline docstring.
This is a multiline docstring.
This is a multiline docstring.
'''
pass
def foo():
"""This is a docstring with
some lines of text here
"""
return
def baz():
'''"This" is a string with some
embedded "quotes"'''
return
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 believe_it_or_not_this_is_in_the_py_stdlib():
'''
"hey yah"'''
def shockingly_the_quotes_are_normalized_v2():
'''
Docstring Docstring Docstring
'''
pass
def backslash_space():
'\ '
def multiline_backslash_1():
'''
hey\there\
\ '''
def multiline_backslash_2():
'''
hey there \ '''
def multiline_backslash_3():
'''
already escaped \\'''
| python | MIT | c3cc5a95d4f72e6ccc27ebae23344fce8cc70786 | 2026-01-04T14:40:23.735327Z | false |
psf/black | https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/fmtskip5.py | tests/data/cases/fmtskip5.py | a, b, c = 3, 4, 5
if (
a == 3
and b != 9 # fmt: skip
and c is not None
):
print("I'm good!")
else:
print("I'm bad")
# output
a, b, c = 3, 4, 5
if (
a == 3
and b != 9 # fmt: skip
and c is not None
):
print("I'm good!")
else:
print("I'm bad")
| python | MIT | c3cc5a95d4f72e6ccc27ebae23344fce8cc70786 | 2026-01-04T14:40:23.735327Z | false |
psf/black | https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/fstring.py | tests/data/cases/fstring.py | f"f-string without formatted values is just a string"
f"{{NOT a formatted value}}"
f"{{NOT 'a' \"formatted\" \"value\"}}"
f"some f-string with {a} {few():.2f} {formatted.values!r}"
f'some f-string with {a} {few(""):.2f} {formatted.values!r}'
f"{f'''{'nested'} inner'''} outer"
f"\"{f'{nested} inner'}\" outer"
f"space between opening braces: { {a for a in (1, 2, 3)}}"
f'Hello \'{tricky + "example"}\''
f"Tried directories {str(rootdirs)} \
but none started with prefix {parentdir_prefix}"
# output
f"f-string without formatted values is just a string"
f"{{NOT a formatted value}}"
f'{{NOT \'a\' "formatted" "value"}}'
f"some f-string with {a} {few():.2f} {formatted.values!r}"
f'some f-string with {a} {few(""):.2f} {formatted.values!r}'
f"{f'''{'nested'} inner'''} outer"
f"\"{f'{nested} inner'}\" outer"
f"space between opening braces: { {a for a in (1, 2, 3)}}"
f'Hello \'{tricky + "example"}\''
f"Tried directories {str(rootdirs)} \
but none started with prefix {parentdir_prefix}"
| python | MIT | c3cc5a95d4f72e6ccc27ebae23344fce8cc70786 | 2026-01-04T14:40:23.735327Z | false |
psf/black | https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/jupytext_markdown_fmt.py | tests/data/cases/jupytext_markdown_fmt.py | # Test that Jupytext markdown comments are preserved before fmt:off/on blocks
# %% [markdown]
# fmt: off
# fmt: on
# Also test with other comments
# Some comment
# %% [markdown]
# Another comment
# fmt: off
x = 1
# fmt: on
# Test multiple markdown comments
# %% [markdown]
# First markdown
# %% [code]
# Code cell
# fmt: off
y = 2
# fmt: on | python | MIT | c3cc5a95d4f72e6ccc27ebae23344fce8cc70786 | 2026-01-04T14:40:23.735327Z | false |
psf/black | https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/comments4.py | tests/data/cases/comments4.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
)
class C:
@pytest.mark.parametrize(
("post_data", "message"),
[
# metadata_version errors.
(
{},
"None is an invalid value for Metadata-Version. Error: This field is"
" required. see"
" https://packaging.python.org/specifications/core-metadata",
),
(
{"metadata_version": "-1"},
"'-1' is an invalid value for Metadata-Version. Error: Unknown Metadata"
" Version see"
" https://packaging.python.org/specifications/core-metadata",
),
# name errors.
(
{"metadata_version": "1.2"},
"'' is an invalid value for Name. Error: This field is required. see"
" https://packaging.python.org/specifications/core-metadata",
),
(
{"metadata_version": "1.2", "name": "foo-"},
"'foo-' is an invalid value for Name. Error: Must start and end with a"
" letter or numeral and contain only ascii numeric and '.', '_' and"
" '-'. see https://packaging.python.org/specifications/core-metadata",
),
# version errors.
(
{"metadata_version": "1.2", "name": "example"},
"'' is an invalid value for Version. Error: This field is required. see"
" https://packaging.python.org/specifications/core-metadata",
),
(
{"metadata_version": "1.2", "name": "example", "version": "dog"},
"'dog' is an invalid value for Version. Error: Must start and end with"
" a letter or numeral and contain only ascii numeric and '.', '_' and"
" '-'. see https://packaging.python.org/specifications/core-metadata",
),
],
)
def test_fails_invalid_post_data(
self, pyramid_config, db_request, post_data, message
):
pyramid_config.testing_securitypolicy(userid=1)
db_request.POST = MultiDict(post_data)
def foo(list_a, list_b):
results = (
User.query.filter(User.foo == "bar")
.filter( # Because foo.
db.or_(User.field_a.astext.in_(list_a), User.field_b.astext.in_(list_b))
)
.filter(User.xyz.is_(None))
# Another comment about the filtering on is_quux goes here.
.filter(db.not_(User.is_pending.astext.cast(db.Boolean).is_(True)))
.order_by(User.created_at.desc())
.with_for_update(key_share=True)
.all()
)
return results
def foo2(list_a, list_b):
# Standalone comment reasonably placed.
return (
User.query.filter(User.foo == "bar")
.filter(
db.or_(User.field_a.astext.in_(list_a), User.field_b.astext.in_(list_b))
)
.filter(User.xyz.is_(None))
)
def foo3(list_a, list_b):
return (
# Standalone comment but weirdly placed.
User.query.filter(User.foo == "bar")
.filter(
db.or_(User.field_a.astext.in_(list_a), User.field_b.astext.in_(list_b))
)
.filter(User.xyz.is_(None))
)
| python | MIT | c3cc5a95d4f72e6ccc27ebae23344fce8cc70786 | 2026-01-04T14:40:23.735327Z | false |
psf/black | https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/comments9.py | tests/data/cases/comments9.py | # Test for https://github.com/psf/black/issues/246.
some = statement
# This comment should be split from the statement above by two lines.
def function():
pass
some = statement
# This multiline comments section
# should be split from the statement
# above by two lines.
def function():
pass
some = statement
# This comment should be split from the statement above by two lines.
async def async_function():
pass
some = statement
# This comment should be split from the statement above by two lines.
class MyClass:
pass
some = statement
# This should be stick to the statement above
# This should be split from the above by two lines
class MyClassWithComplexLeadingComments:
pass
class ClassWithDocstring:
"""A docstring."""
# Leading comment after a class with just a docstring
class MyClassAfterAnotherClassWithDocstring:
pass
some = statement
# leading 1
@deco1
# leading 2
# leading 2 extra
@deco2(with_args=True)
# leading 3
@deco3
# leading 4
def decorated():
pass
some = statement
# leading 1
@deco1
# leading 2
@deco2(with_args=True)
# leading 3 that already has an empty line
@deco3
# leading 4
def decorated_with_split_leading_comments():
pass
some = statement
# leading 1
@deco1
# leading 2
@deco2(with_args=True)
# leading 3
@deco3
# leading 4 that already has an empty line
def decorated_with_split_leading_comments():
pass
def main():
if a:
# Leading comment before inline function
def inline():
pass
# Another leading comment
def another_inline():
pass
else:
# More leading comments
def inline_after_else():
pass
if a:
# Leading comment before "top-level inline" function
def top_level_quote_inline():
pass
# Another leading comment
def another_top_level_quote_inline_inline():
pass
else:
# More leading comments
def top_level_quote_inline_after_else():
pass
class MyClass:
# First method has no empty lines between bare class def.
# More comments.
def first_method(self):
pass
# Regression test for https://github.com/psf/black/issues/3454.
def foo():
pass
# Trailing comment that belongs to this function
@decorator1
@decorator2 # fmt: skip
def bar():
pass
# Regression test for https://github.com/psf/black/issues/3454.
def foo():
pass
# Trailing comment that belongs to this function.
# NOTE this comment only has one empty line below, and the formatter
# should enforce two blank lines.
@decorator1
# A standalone comment
def bar():
pass
# output
# Test for https://github.com/psf/black/issues/246.
some = statement
# This comment should be split from the statement above by two lines.
def function():
pass
some = statement
# This multiline comments section
# should be split from the statement
# above by two lines.
def function():
pass
some = statement
# This comment should be split from the statement above by two lines.
async def async_function():
pass
some = statement
# This comment should be split from the statement above by two lines.
class MyClass:
pass
some = statement
# This should be stick to the statement above
# This should be split from the above by two lines
class MyClassWithComplexLeadingComments:
pass
class ClassWithDocstring:
"""A docstring."""
# Leading comment after a class with just a docstring
class MyClassAfterAnotherClassWithDocstring:
pass
some = statement
# leading 1
@deco1
# leading 2
# leading 2 extra
@deco2(with_args=True)
# leading 3
@deco3
# leading 4
def decorated():
pass
some = statement
# leading 1
@deco1
# leading 2
@deco2(with_args=True)
# leading 3 that already has an empty line
@deco3
# leading 4
def decorated_with_split_leading_comments():
pass
some = statement
# leading 1
@deco1
# leading 2
@deco2(with_args=True)
# leading 3
@deco3
# leading 4 that already has an empty line
def decorated_with_split_leading_comments():
pass
def main():
if a:
# Leading comment before inline function
def inline():
pass
# Another leading comment
def another_inline():
pass
else:
# More leading comments
def inline_after_else():
pass
if a:
# Leading comment before "top-level inline" function
def top_level_quote_inline():
pass
# Another leading comment
def another_top_level_quote_inline_inline():
pass
else:
# More leading comments
def top_level_quote_inline_after_else():
pass
class MyClass:
# First method has no empty lines between bare class def.
# More comments.
def first_method(self):
pass
# Regression test for https://github.com/psf/black/issues/3454.
def foo():
pass
# Trailing comment that belongs to this function
@decorator1
@decorator2 # fmt: skip
def bar():
pass
# Regression test for https://github.com/psf/black/issues/3454.
def foo():
pass
# Trailing comment that belongs to this function.
# NOTE this comment only has one empty line below, and the formatter
# should enforce two blank lines.
@decorator1
# A standalone comment
def bar():
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_38.py | tests/data/cases/context_managers_autodetect_38.py | # This file doesn't use any Python 3.9+ only grammars.
# Make sure parens around a single context manager don't get autodetected as
# Python 3.9+.
with (a):
pass
with \
make_context_manager1() as cm1, \
make_context_manager2() as cm2, \
make_context_manager3() as cm3, \
make_context_manager4() as cm4 \
:
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
# This file doesn't use any Python 3.9+ only grammars.
# Make sure parens around a single context manager don't get autodetected as
# Python 3.9+.
with a:
pass
with make_context_manager1() as cm1, make_context_manager2() as cm2, make_context_manager3() as cm3, make_context_manager4() as cm4:
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_hug_parens_with_braces_and_square_brackets.py | tests/data/cases/preview_hug_parens_with_braces_and_square_brackets.py | # flags: --unstable
def foo_brackets(request):
return JsonResponse(
{
"var_1": foo,
"var_2": bar,
}
)
def foo_square_brackets(request):
return JsonResponse(
[
"var_1",
"var_2",
]
)
func({"a": 37, "b": 42, "c": 927, "aaaaaaaaaaaaaaaaaaaaaaaaa": 11111111111111111111111111111111111111111})
func(["random_string_number_one","random_string_number_two","random_string_number_three","random_string_number_four"])
func(
{
# expand me
'a':37,
'b':42,
'c':927
}
)
func(
[
'a',
'b',
'c',
]
)
func(
[
'a',
'b',
'c',
],
)
func( # a
[ # b
"c", # c
"d", # d
"e", # e
] # f
) # g
func( # a
{ # b
"c": 1, # c
"d": 2, # d
"e": 3, # e
} # f
) # g
func(
# preserve me
[
"c",
"d",
"e",
]
)
func(
[ # preserve me but hug brackets
"c",
"d",
"e",
]
)
func(
[
# preserve me but hug brackets
"c",
"d",
"e",
]
)
func(
[
"c",
# preserve me but hug brackets
"d",
"e",
]
)
func(
[
"c",
"d",
"e",
# preserve me but hug brackets
]
)
func(
[
"c",
"d",
"e",
] # preserve me but hug brackets
)
func(
[
"c",
"d",
"e",
]
# preserve me
)
func([x for x in "short line"])
func([x for x in "long line long line long line long line long line long line long line"])
func([x for x in [x for x in "long line long line long line long line long line long line long line"]])
foooooooooooooooooooo(
[{c: n + 1 for c in range(256)} for n in range(100)] + [{}], {size}
)
baaaaaaaaaaaaar(
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], {x}, "a string", [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
)
nested_mapping = {"key": [{"a very long key 1": "with a very long value", "a very long key 2": "with a very long value"}]}
explicit_exploding = [[["short", "line",],],]
single_item_do_not_explode = Context({
"version": get_docs_version(),
})
foo(*[str(i) for i in range(100000000000000000000000000000000000000000000000000000000000)])
foo(
**{
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa": 1,
"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb": 2,
"ccccccccccccccccccccccccccccccccc": 3,
**other,
}
)
foo(**{x: y for x, y in enumerate(["long long long long line","long long long long line"])})
# Edge case when deciding whether to hug the brackets without inner content.
very_very_very_long_variable = very_very_very_long_module.VeryVeryVeryVeryLongClassName([[]])
for foo in ["a", "b"]:
output.extend([
individual
for
# Foobar
container in xs_by_y[foo]
# Foobar
for individual in container["nested"]
])
# output
def foo_brackets(request):
return JsonResponse({
"var_1": foo,
"var_2": bar,
})
def foo_square_brackets(request):
return JsonResponse([
"var_1",
"var_2",
])
func({
"a": 37,
"b": 42,
"c": 927,
"aaaaaaaaaaaaaaaaaaaaaaaaa": 11111111111111111111111111111111111111111,
})
func([
"random_string_number_one",
"random_string_number_two",
"random_string_number_three",
"random_string_number_four",
])
func({
# expand me
"a": 37,
"b": 42,
"c": 927,
})
func([
"a",
"b",
"c",
])
func(
[
"a",
"b",
"c",
],
)
func([ # a # b
"c", # c
"d", # d
"e", # e
]) # f # g
func({ # a # b
"c": 1, # c
"d": 2, # d
"e": 3, # e
}) # f # g
func(
# preserve me
[
"c",
"d",
"e",
]
)
func([ # preserve me but hug brackets
"c",
"d",
"e",
])
func([
# preserve me but hug brackets
"c",
"d",
"e",
])
func([
"c",
# preserve me but hug brackets
"d",
"e",
])
func([
"c",
"d",
"e",
# preserve me but hug brackets
])
func([
"c",
"d",
"e",
]) # preserve me but hug brackets
func(
[
"c",
"d",
"e",
]
# preserve me
)
func([x for x in "short line"])
func(
[x for x in "long line long line long line long line long line long line long line"]
)
func([
x
for x in [
x
for x in "long line long line long line long line long line long line long line"
]
])
foooooooooooooooooooo(
[{c: n + 1 for c in range(256)} for n in range(100)] + [{}], {size}
)
baaaaaaaaaaaaar(
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], {x}, "a string", [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
)
nested_mapping = {
"key": [{
"a very long key 1": "with a very long value",
"a very long key 2": "with a very long value",
}]
}
explicit_exploding = [
[
[
"short",
"line",
],
],
]
single_item_do_not_explode = Context({
"version": get_docs_version(),
})
foo(*[
str(i) for i in range(100000000000000000000000000000000000000000000000000000000000)
])
foo(**{
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa": 1,
"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb": 2,
"ccccccccccccccccccccccccccccccccc": 3,
**other,
})
foo(**{
x: y for x, y in enumerate(["long long long long line", "long long long long line"])
})
# Edge case when deciding whether to hug the brackets without inner content.
very_very_very_long_variable = very_very_very_long_module.VeryVeryVeryVeryLongClassName(
[[]]
)
for foo in ["a", "b"]:
output.extend([
individual
for
# Foobar
container in xs_by_y[foo]
# Foobar
for individual in container["nested"]
])
| 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.py | tests/data/cases/preview_long_strings.py | # flags: --unstable
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)}
D5 = { # Test for https://github.com/psf/black/issues/3261
("This is a really long string that can't be expected to fit in one line and is used as a nested dict's key"): {"inner": "value"},
}
D6 = { # Test for https://github.com/psf/black/issues/3261
("This is a really long string that can't be expected to fit in one line and is used as a dict's key"): ["value1", "value2"],
}
L1 = ["The is a short string", "This is a really long string that can't possibly be expected to fit all together on one line. Also it is inside a list literal, so it's expected to be wrapped in parens when splitting to avoid implicit str concatenation.", short_call("arg", {"key": "value"}), "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 list literal.", ("parens should be stripped for short string in list")]
L2 = ["This is a really long string that can't be expected to fit in one line and is the only child of a list literal."]
S1 = {"The is a short string", "This is a really long string that can't possibly be expected to fit all together on one line. Also it is inside a set literal, so it's expected to be wrapped in parens when splitting to avoid implicit str concatenation.", short_call("arg", {"key": "value"}), "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 set literal.", ("parens should be stripped for short string in set")}
S2 = {"This is a really long string that can't be expected to fit in one line and is the only child of a set literal."}
T1 = ("The is a short string", "This is a really long string that can't possibly be expected to fit all together on one line. Also it is inside a tuple literal, so it's expected to be wrapped in parens when splitting to avoid implicit str concatenation.", short_call("arg", {"key": "value"}), "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 tuple literal.", ("parens should be stripped for short string in list"))
T2 = ("This is a really long string that can't be expected to fit in one line and is the only child of a tuple literal.",)
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,
)
inline_comments_func1(
"if there are inline "
"comments in the middle "
# Here is the standard alone comment.
"of the implicitly concatenated "
"string, we should handle "
"them correctly",
xxx,
)
inline_comments_func2(
"what if the string is very very very very very very very very very very long and this part does "
"not fit into a single line? "
# Here is the standard alone comment.
"then the string should still be properly handled by merging and splitting "
"it into parts that fit in line length.",
xxx,
)
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 gets thrown to the top.
"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."
)
string_with_nameescape = (
"........................................................................ \N{LAO KO LA}"
)
string_with_nameescape = (
"........................................................................... \N{LAO KO LA}"
)
string_with_nameescape = (
"............................................................................ \N{LAO KO LA}"
)
string_with_nameescape_and_escaped_backslash = (
"...................................................................... \\\N{LAO KO LA}"
)
string_with_nameescape_and_escaped_backslash = (
"......................................................................... \\\N{LAO KO LA}"
)
string_with_nameescape_and_escaped_backslash = (
".......................................................................... \\\N{LAO KO LA}"
)
string_with_escaped_nameescape = (
"........................................................................ \\N{LAO KO LA}"
)
string_with_escaped_nameescape = (
"........................................................................... \\N{LAO KO LA}"
)
msg = lambda x: f"this is a very very very very long lambda value {x} that doesn't fit on a single line"
dict_with_lambda_values = {
"join": lambda j: (
f"{j.__class__.__name__}({some_function_call(j.left)}, "
f"{some_function_call(j.right)})"
),
}
# Complex string concatenations with a method call in the middle.
code = (
(" return [\n")
+ (
", \n".join(
" (%r, self.%s, visitor.%s)"
% (attrname, attrname, visit_name)
for attrname, visit_name in names
)
)
+ ("\n ]\n")
)
# Test case of an outer string' parens enclose an inner string's parens.
call(body=("%s %s" % ((",".join(items)), suffix)))
log.info(f'Skipping: {desc["db_id"]=} {desc["ms_name"]} {money=} {dte=} {pos_share=} {desc["status"]=} {desc["exposure_max"]=}')
log.info(f"Skipping: {desc['db_id']=} {desc['ms_name']} {money=} {dte=} {pos_share=} {desc['status']=} {desc['exposure_max']=}")
log.info(f'Skipping: {desc["db_id"]} {foo("bar",x=123)} {"foo" != "bar"} {(x := "abc=")} {pos_share=} {desc["status"]} {desc["exposure_max"]}')
log.info(f'Skipping: {desc["db_id"]} {desc["ms_name"]} {money=} {(x := "abc=")=} {pos_share=} {desc["status"]} {desc["exposure_max"]}')
log.info(f'Skipping: {desc["db_id"]} {foo("bar",x=123)=} {money=} {dte=} {pos_share=} {desc["status"]} {desc["exposure_max"]}')
log.info(f'Skipping: {foo("asdf")=} {desc["ms_name"]} {money=} {dte=} {pos_share=} {desc["status"]} {desc["exposure_max"]}')
log.info(f'Skipping: {"a" == "b" == "c" == "d"} {desc["ms_name"]} {money=} {dte=} {pos_share=} {desc["status"]} {desc["exposure_max"]}')
log.info(f'Skipping: {"a" == "b" == "c" == "d"=} {desc["ms_name"]} {money=} {dte=} {pos_share=} {desc["status"]} {desc["exposure_max"]}')
log.info(f'Skipping: { longer_longer_longer_longer_longer_longer_name [ "db_id" ] [ "another_key" ] = : .3f }')
log.info(f'''Skipping: {"a" == 'b'} {desc["ms_name"]} {money=} {dte=} {pos_share=} {desc["status"]} {desc["exposure_max"]}''')
log.info(f'''Skipping: {'a' == "b"=} {desc["ms_name"]} {money=} {dte=} {pos_share=} {desc["status"]} {desc["exposure_max"]}''')
log.info(f"""Skipping: {'a' == 'b'} {desc['ms_name']} {money=} {dte=} {pos_share=} {desc['status']} {desc['exposure_max']}""")
x = {
"xx_xxxxx_xxxxxxxxxx_xxxxxxxxx_xx": (
"xx:xxxxxxxxxxxxxxxxx_xxxxx_xxxxxxx_xxxxxxxxxxx{xx}xxx_xxxxx_xxxxxxxxx_xxxxxxxxxxxx_xxxx"
)
}
x = {
"xx_xxxxx_xxxxxxxxxx_xxxxxxxxx_xx": "xx:xxxxxxxxxxxxxxxxx_xxxxx_xxxxxxx_xxxxxxxxxxx{xx}xxx_xxxxx_xxxxxxxxx_xxxxxxxxxxxx_xxxx",
}
x = {
"xx_xxxxx_xxxxxxxxxx_xxxxxxxxx_xx": (
"xx:xxxxxxxxxxxxxxxxx_xxxxx_xxxxxxx_xxxxxxxxxx"
)
}
# output
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)
),
}
D5 = { # Test for https://github.com/psf/black/issues/3261
"This is a really long string that can't be expected to fit in one line and is used as a nested dict's key": {
"inner": "value"
},
}
D6 = { # Test for https://github.com/psf/black/issues/3261
"This is a really long string that can't be expected to fit in one line and is used as a dict's key": [
"value1",
"value2",
],
}
L1 = [
"The is a short string",
(
"This is a really long string that can't possibly be expected to fit all"
" together on one line. Also it is inside a list literal, so it's expected to"
" be wrapped in parens when splitting to avoid implicit str concatenation."
),
short_call("arg", {"key": "value"}),
(
"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 list"
" literal."
),
"parens should be stripped for short string in list",
]
L2 = [
"This is a really long string that can't be expected to fit in one line and is the"
" only child of a list literal."
]
S1 = {
"The is a short string",
(
"This is a really long string that can't possibly be expected to fit all"
" together on one line. Also it is inside a set literal, so it's expected to be"
" wrapped in parens when splitting to avoid implicit str concatenation."
),
short_call("arg", {"key": "value"}),
(
"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 set"
" literal."
),
"parens should be stripped for short string in set",
}
S2 = {
"This is a really long string that can't be expected to fit in one line and is the"
" only child of a set literal."
}
T1 = (
"The is a short string",
(
"This is a really long string that can't possibly be expected to fit all"
" together on one line. Also it is inside a tuple literal, so it's expected to"
" be wrapped in parens when splitting to avoid implicit str concatenation."
),
short_call("arg", {"key": "value"}),
(
"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 tuple"
" literal."
),
"parens should be stripped for short string in list",
)
T2 = (
(
"This is a really long string that can't be expected to fit in one line and is"
" the only child of a tuple literal."
),
)
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,
)
inline_comments_func1(
"if there are inline comments in the middle "
# Here is the standard alone comment.
"of the implicitly concatenated string, we should handle them correctly",
xxx,
)
inline_comments_func2(
"what if the string is very very very very very very very very very very long and"
" this part does not fit into a single line? "
# Here is the standard alone comment.
"then the string should still be properly handled by merging and splitting "
"it into parts that fit in line length.",
xxx,
)
raw_string = (
r"This is a long raw string. When re-formatting this string, black needs to make"
r" 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"
f" 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"
f" any means whatsoever."
)
comment_string = ( # This comment gets thrown to the top.
"Long lines with inline comments should have their comments appended to the"
" reformatted string's enclosing right parentheses."
)
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 gets thrown to the top.
"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 = (
"This is a {really} long string that needs to be split without a doubt (i.e."
f" most definitely). In short, this {string} that can't possibly be {{expected}} to"
| python | MIT | c3cc5a95d4f72e6ccc27ebae23344fce8cc70786 | 2026-01-04T14:40:23.735327Z | true |
psf/black | https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/allow_empty_first_line.py | tests/data/cases/allow_empty_first_line.py | def foo():
"""
Docstring
"""
# Here we go
if x:
# This is also now fine
a = 123
else:
# But not necessary
a = 123
if y:
while True:
"""
Long comment here
"""
a = 123
if z:
for _ in range(100):
a = 123
else:
try:
# this should be ok
a = 123
except:
"""also this"""
a = 123
def bar():
if x:
a = 123
def baz():
# OK
if x:
a = 123
def quux():
new_line = here
class Cls:
def method(self):
pass
async def async_fn():
"""Docstring."""
@decorated
async def async_fn():
"""Docstring."""
def top_level(
a: int,
b: str,
) -> Whatever[Generic, Something]:
def nested(x: int) -> int:
pass
# output
def foo():
"""
Docstring
"""
# Here we go
if x:
# This is also now fine
a = 123
else:
# But not necessary
a = 123
if y:
while True:
"""
Long comment here
"""
a = 123
if z:
for _ in range(100):
a = 123
else:
try:
# this should be ok
a = 123
except:
"""also this"""
a = 123
def bar():
if x:
a = 123
def baz():
# OK
if x:
a = 123
def quux():
new_line = here
class Cls:
def method(self):
pass
async def async_fn():
"""Docstring."""
@decorated
async def async_fn():
"""Docstring."""
def top_level(
a: int,
b: str,
) -> Whatever[Generic, Something]:
def nested(x: int) -> int:
pass
| 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.py | tests/data/cases/prefer_rhs_split.py | first_item, second_item = (
some_looooooooong_module.some_looooooooooooooong_function_name(
first_argument, second_argument, third_argument
)
)
some_dict["with_a_long_key"] = (
some_looooooooong_module.some_looooooooooooooong_function_name(
first_argument, second_argument, third_argument
)
)
# Make sure it works when the RHS only has one pair of (optional) parens.
first_item, second_item = (
some_looooooooong_module.SomeClass.some_looooooooooooooong_variable_name
)
some_dict["with_a_long_key"] = (
some_looooooooong_module.SomeClass.some_looooooooooooooong_variable_name
)
# Make sure chaining assignments work.
first_item, second_item, third_item, forth_item = m["everything"] = (
some_looooooooong_module.some_looooooooooooooong_function_name(
first_argument, second_argument, third_argument
)
)
# Make sure when the RHS's first split at the non-optional paren fits,
# we split there instead of the outer RHS optional paren.
first_item, second_item = some_looooooooong_module.some_loooooog_function_name(
first_argument, second_argument, third_argument
)
(
first_item,
second_item,
third_item,
forth_item,
fifth_item,
last_item_very_loooooong,
) = some_looooooooong_module.some_looooooooooooooong_function_name(
first_argument, second_argument, third_argument
)
(
first_item,
second_item,
third_item,
forth_item,
fifth_item,
last_item_very_loooooong,
) = everything = some_looooong_function_name(
first_argument, second_argument, third_argument
)
# Make sure unsplittable type ignore won't be moved.
some_kind_of_table[some_key] = util.some_function( # type: ignore # noqa: E501
some_arg
).intersection(pk_cols)
some_kind_of_table[
some_key
] = lambda obj: obj.some_long_named_method() # type: ignore # noqa: E501
some_kind_of_table[
some_key # type: ignore # noqa: E501
] = lambda obj: obj.some_long_named_method()
# 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
# Right side of assignment contains un-nested pairs of inner parens.
some_kind_of_instance.some_kind_of_map[a_key] = (
isinstance(some_var, SomeClass)
and table.something_and_something != table.something_else
) or (
isinstance(some_other_var, BaseClass) and table.something != table.some_other_thing
)
# Multiple targets
a = b = (
ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc
)
a = b = c = d = e = f = g = (
hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh
) = i = j = (
kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
)
a = (
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
) = c
a = (
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
) = (
cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc
) = ddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd
| python | MIT | c3cc5a95d4f72e6ccc27ebae23344fce8cc70786 | 2026-01-04T14:40:23.735327Z | false |
psf/black | https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/slices.py | tests/data/cases/slices.py | slice[a.b : c.d]
slice[d :: d + 1]
slice[d + 1 :: d]
slice[d::d]
slice[0]
slice[-1]
slice[:-1]
slice[::-1]
slice[:c, c - 1]
slice[c, c + 1, d::]
slice[ham[c::d] :: 1]
slice[ham[cheese**2 : -1] : 1 : 1, ham[1:2]]
slice[:-1:]
slice[lambda: None : lambda: None]
slice[lambda x, y, *args, really=2, **kwargs: None :, None::]
slice[1 or 2 : True and False]
slice[not so_simple : 1 < val <= 10]
slice[(1 for i in range(42)) : x]
slice[:: [i for i in range(42)]]
async def f():
slice[await x : [i async for i in arange(42)] : 42]
# These are from PEP-8:
ham[1:9], ham[1:9:3], ham[:9:3], ham[1::3], ham[1:9:]
ham[lower:upper], ham[lower:upper:], ham[lower::step]
# ham[lower+offset : upper+offset]
ham[: upper_fn(x) : step_fn(x)], ham[:: step_fn(x)]
ham[lower + offset : upper + offset]
| python | MIT | c3cc5a95d4f72e6ccc27ebae23344fce8cc70786 | 2026-01-04T14:40:23.735327Z | false |
psf/black | https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/line_ranges_exceeding_end.py | tests/data/cases/line_ranges_exceeding_end.py | # flags: --line-ranges=6-1000
# 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
# output
# flags: --line-ranges=6-1000
# 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
| python | MIT | c3cc5a95d4f72e6ccc27ebae23344fce8cc70786 | 2026-01-04T14:40:23.735327Z | false |
psf/black | https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/pep_572_slices.py | tests/data/cases/pep_572_slices.py | x[(a:=0):]
x[:(a:=0)]
# output
x[(a := 0) :]
x[: (a := 0)]
| python | MIT | c3cc5a95d4f72e6ccc27ebae23344fce8cc70786 | 2026-01-04T14:40:23.735327Z | false |
psf/black | https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/remove_except_parens.py | tests/data/cases/remove_except_parens.py | # These brackets are redundant, therefore remove.
try:
a.something
except (AttributeError) as err:
raise err
# This is tuple of exceptions.
# Although this could be replaced with just the exception,
# we do not remove brackets to preserve AST.
try:
a.something
except (AttributeError,) as err:
raise err
# This is a tuple of exceptions. Do not remove brackets.
try:
a.something
except (AttributeError, ValueError) as err:
raise err
# Test long variants.
try:
a.something
except (some.really.really.really.looooooooooooooooooooooooooooooooong.module.over89.chars.Error) as err:
raise err
try:
a.something
except (some.really.really.really.looooooooooooooooooooooooooooooooong.module.over89.chars.Error,) as err:
raise err
try:
a.something
except (some.really.really.really.looooooooooooooooooooooooooooooooong.module.over89.chars.Error, some.really.really.really.looooooooooooooooooooooooooooooooong.module.over89.chars.Error) as err:
raise err
# output
# These brackets are redundant, therefore remove.
try:
a.something
except AttributeError as err:
raise err
# This is tuple of exceptions.
# Although this could be replaced with just the exception,
# we do not remove brackets to preserve AST.
try:
a.something
except (AttributeError,) as err:
raise err
# This is a tuple of exceptions. Do not remove brackets.
try:
a.something
except (AttributeError, ValueError) as err:
raise err
# Test long variants.
try:
a.something
except (
some.really.really.really.looooooooooooooooooooooooooooooooong.module.over89.chars.Error
) as err:
raise err
try:
a.something
except (
some.really.really.really.looooooooooooooooooooooooooooooooong.module.over89.chars.Error,
) as err:
raise err
try:
a.something
except (
some.really.really.really.looooooooooooooooooooooooooooooooong.module.over89.chars.Error,
some.really.really.really.looooooooooooooooooooooooooooooooong.module.over89.chars.Error,
) as err:
raise err
| python | MIT | c3cc5a95d4f72e6ccc27ebae23344fce8cc70786 | 2026-01-04T14:40:23.735327Z | false |
psf/black | https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/preview_comments7.py | tests/data/cases/preview_comments7.py | # flags: --unstable
from .config import (
Any,
Bool,
ConfigType,
ConfigTypeAttributes,
Int,
Path,
# String,
# resolve_to_config_type,
# DEFAULT_TYPE_ATTRIBUTES,
)
from .config import (
Any,
Bool,
ConfigType,
ConfigTypeAttributes,
Int,
no_comma_here_yet
# and some comments,
# resolve_to_config_type,
# DEFAULT_TYPE_ATTRIBUTES,
)
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
)
result = 1 # look ma, no comment migration xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
result = (
1 # look ma, no comment migration xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
)
result = (
"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" # aaa
)
result = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" # aaa
def func():
c = call(
0.0123,
0.0456,
0.0789,
0.0123,
0.0789,
a[-1], # type: ignore
)
c = call(
0.0123,
0.0456,
0.0789,
0.0123,
0.0789,
a[-1] # type: ignore
)
c = call(
0.0123,
0.0456,
0.0789,
0.0123,
0.0456,
0.0789,
0.0123,
0.0456,
0.0789,
a[-1] # type: ignore
)
# The type: ignore exception only applies to line length, not
# other types of formatting.
c = call(
"aaaaaaaa", "aaaaaaaa", "aaaaaaaa", "aaaaaaaa", "aaaaaaaa", "aaaaaaaa", # type: ignore
"aaaaaaaa", "aaaaaaaa", "aaaaaaaa", "aaaaaaaa", "aaaaaaaa", "aaaaaaaa"
)
class C:
@pytest.mark.parametrize(
("post_data", "message"),
[
# metadata_version errors.
(
{},
"None is an invalid value for Metadata-Version. Error: This field is"
" required. see"
" https://packaging.python.org/specifications/core-metadata"
),
(
{"metadata_version": "-1"},
"'-1' is an invalid value for Metadata-Version. Error: Unknown Metadata"
" Version see"
" https://packaging.python.org/specifications/core-metadata"
),
# name errors.
(
{"metadata_version": "1.2"},
"'' is an invalid value for Name. Error: This field is required. see"
" https://packaging.python.org/specifications/core-metadata"
),
(
{"metadata_version": "1.2", "name": "foo-"},
"'foo-' is an invalid value for Name. Error: Must start and end with a"
" letter or numeral and contain only ascii numeric and '.', '_' and"
" '-'. see https://packaging.python.org/specifications/core-metadata"
),
# version errors.
(
{"metadata_version": "1.2", "name": "example"},
"'' is an invalid value for Version. Error: This field is required. see"
" https://packaging.python.org/specifications/core-metadata"
),
(
{"metadata_version": "1.2", "name": "example", "version": "dog"},
"'dog' is an invalid value for Version. Error: Must start and end with"
" a letter or numeral and contain only ascii numeric and '.', '_' and"
" '-'. see https://packaging.python.org/specifications/core-metadata"
)
]
)
def test_fails_invalid_post_data(
self, pyramid_config, db_request, post_data, message
):
...
square = Square(4) # type: Optional[Square]
# Regression test for https://github.com/psf/black/issues/3756.
[
(
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" # aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
),
]
[
( # aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" # aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
),
]
# output
from .config import (
Any,
Bool,
ConfigType,
ConfigTypeAttributes,
Int,
Path,
# String,
# resolve_to_config_type,
# DEFAULT_TYPE_ATTRIBUTES,
)
from .config import (
Any,
Bool,
ConfigType,
ConfigTypeAttributes,
Int,
no_comma_here_yet,
# and some comments,
# resolve_to_config_type,
# DEFAULT_TYPE_ATTRIBUTES,
)
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
)
result = 1 # look ma, no comment migration xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
result = 1 # look ma, no comment migration xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
result = ( # aaa
"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
)
result = ( # aaa
"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
)
def func():
c = call(
0.0123,
0.0456,
0.0789,
0.0123,
0.0789,
a[-1], # type: ignore
)
c = call(0.0123, 0.0456, 0.0789, 0.0123, 0.0789, a[-1]) # type: ignore
c = call(
0.0123,
0.0456,
0.0789,
0.0123,
0.0456,
0.0789,
0.0123,
0.0456,
0.0789,
a[-1], # type: ignore
)
# The type: ignore exception only applies to line length, not
# other types of formatting.
c = call(
"aaaaaaaa",
"aaaaaaaa",
"aaaaaaaa",
"aaaaaaaa",
"aaaaaaaa",
"aaaaaaaa", # type: ignore
"aaaaaaaa",
"aaaaaaaa",
"aaaaaaaa",
"aaaaaaaa",
"aaaaaaaa",
"aaaaaaaa",
)
class C:
@pytest.mark.parametrize(
("post_data", "message"),
[
# metadata_version errors.
(
{},
(
"None is an invalid value for Metadata-Version. Error: This field"
" is required. see"
" https://packaging.python.org/specifications/core-metadata"
),
),
(
{"metadata_version": "-1"},
(
"'-1' is an invalid value for Metadata-Version. Error: Unknown"
" Metadata Version see"
" https://packaging.python.org/specifications/core-metadata"
),
),
# name errors.
(
{"metadata_version": "1.2"},
(
"'' is an invalid value for Name. Error: This field is required."
" see https://packaging.python.org/specifications/core-metadata"
),
),
(
{"metadata_version": "1.2", "name": "foo-"},
(
"'foo-' is an invalid value for Name. Error: Must start and end"
" with a letter or numeral and contain only ascii numeric and '.',"
" '_' and '-'. see"
" https://packaging.python.org/specifications/core-metadata"
),
),
# version errors.
(
{"metadata_version": "1.2", "name": "example"},
(
"'' is an invalid value for Version. Error: This field is required."
" see https://packaging.python.org/specifications/core-metadata"
),
),
(
{"metadata_version": "1.2", "name": "example", "version": "dog"},
(
"'dog' is an invalid value for Version. Error: Must start and end"
" with a letter or numeral and contain only ascii numeric and '.',"
" '_' and '-'. see"
" https://packaging.python.org/specifications/core-metadata"
),
),
],
)
def test_fails_invalid_post_data(
self, pyramid_config, db_request, post_data, message
): ...
square = Square(4) # type: Optional[Square]
# Regression test for https://github.com/psf/black/issues/3756.
[
( # aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
),
]
[
( # aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" # aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
),
]
| python | MIT | c3cc5a95d4f72e6ccc27ebae23344fce8cc70786 | 2026-01-04T14:40:23.735327Z | false |
psf/black | https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/numeric_literals_skip_underscores.py | tests/data/cases/numeric_literals_skip_underscores.py | x = 123456789
x = 1_2_3_4_5_6_7
x = 1E+1
x = 0xb1acc
x = 0.00_00_006
x = 12_34_567J
x = .1_2
x = 1_2.
# output
x = 123456789
x = 1_2_3_4_5_6_7
x = 1e1
x = 0xB1ACC
x = 0.00_00_006
x = 12_34_567j
x = 0.1_2
x = 1_2.0 | python | MIT | c3cc5a95d4f72e6ccc27ebae23344fce8cc70786 | 2026-01-04T14:40:23.735327Z | false |
psf/black | https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/preview_long_dict_values.py | tests/data/cases/preview_long_dict_values.py | # flags: --preview
x = {
"xx_xxxxx_xxxxxxxxxx_xxxxxxxxx_xx": (
"xx:xxxxxxxxxxxxxxxxx_xxxxx_xxxxxxx_xxxxxxxxxxx{xx}xxx_xxxxx_xxxxxxxxx_xxxxxxxxxxxx_xxxx"
)
}
x = {
"xx_xxxxx_xxxxxxxxxx_xxxxxxxxx_xx": (
"xx:xxxxxxxxxxxxxxxxx_xxxxx_xxxxxxx_xxxxxxxxxxx{xx}xxx_xxxxx_xxxxxxxxx_xxxxxxxxxxxx_xxxx"
),
}
x = {
"foo": bar,
"foo": bar,
"foo": (
xx_xxxxxxxxxxxxxxxxx_xxxxx_xxxxxxx_xxxxxxxxxxxxxx_xxxxx_xxxxxxxxx_xxxxxxxxxxxx_xxxx
),
}
x = {
"xx_xxxxx_xxxxxxxxxx_xxxxxxxxx_xx": "xx:xxxxxxxxxxxxxxxxx_xxxxx_xxxxxxx_xxxxxxxxxx"
}
my_dict = {
"something_something":
r"Lorem ipsum dolor sit amet, an sed convenire eloquentiam \t"
r"signiferumque, duo ea vocibus consetetur scriptorem. Facer \t"
r"signiferumque, duo ea vocibus consetetur scriptorem. Facer \t",
}
# Function calls as keys
tasks = {
get_key_name(
foo,
bar,
baz,
): src,
loop.run_in_executor(): src,
loop.run_in_executor(xx_xxxxxxxxxxxxxxxxx_xxxxx_xxxxxxx_xxxxxxxxxxxxxx): src,
loop.run_in_executor(
xx_xxxxxxxxxxxxxxxxx_xxxxx_xxxxxxx_xxxxxxxxxxxxxx_xxxxx_xxxxx
): src,
loop.run_in_executor(): (
xx_xxxxxxxxxxxxxxxxx_xxxxx_xxxxxxx_xxxxxxxxxxxxxx_xxxxx_xxxxxxxxx_xxxxxxxxxxxx_xxxx
),
}
# Dictionary comprehensions
tasks = {
key_name: (
xx_xxxxxxxxxxxxxxxxx_xxxxx_xxxxxxx_xxxxxxxxxxxxxx_xxxxx_xxxxxxxxx_xxxxxxxxxxxx_xxxx
)
for src in sources
}
tasks = {key_name: foobar for src in sources}
tasks = {
get_key_name(
src,
): "foo"
for src in sources
}
tasks = {
get_key_name(
foo,
bar,
baz,
): src
for src in sources
}
tasks = {
get_key_name(): (
xx_xxxxxxxxxxxxxxxxx_xxxxx_xxxxxxx_xxxxxxxxxxxxxx_xxxxx_xxxxxxxxx_xxxxxxxxxxxx_xxxx
)
for src in sources
}
tasks = {get_key_name(): foobar for src in sources}
# Delimiters inside the value
def foo():
def bar():
x = {
common.models.DateTimeField: datetime(2020, 1, 31, tzinfo=utc) + timedelta(
days=i
),
}
x = {
common.models.DateTimeField: (
datetime(2020, 1, 31, tzinfo=utc) + timedelta(days=i)
),
}
x = {
"foobar": (123 + 456),
}
x = {
"foobar": (123) + 456,
}
my_dict = {
"a key in my dict": a_very_long_variable * and_a_very_long_function_call() / 100000.0
}
my_dict = {
"a key in my dict": a_very_long_variable * and_a_very_long_function_call() * and_another_long_func() / 100000.0
}
my_dict = {
"a key in my dict": MyClass.some_attribute.first_call().second_call().third_call(some_args="some value")
}
{
"xxxxxx":
xxxxxxxxxxxxxxxxxxx.xxxxxxxxxxxxxx(
xxxxxxxxxxxxxx={
"x":
xxxxxxxxxxxxxxxxxxxxxxxxxx.xxxxxxxxxxxxxxxxxxxxxxxxxxxxx(
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx=(
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
.xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx(
xxxxxxxxxxxxx=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
.xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx(
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx={
"x": x.xx,
"x": x.x,
}))))
}),
}
class Random:
def func():
random_service.status.active_states.inactive = (
make_new_top_level_state_from_dict(
{
"topLevelBase": {
"secondaryBase": {
"timestamp": 1234,
"latitude": 1,
"longitude": 2,
"actionTimestamp": Timestamp(
seconds=1530584000, nanos=0
).ToJsonString(),
}
},
}
)
)
# output
x = {
"xx_xxxxx_xxxxxxxxxx_xxxxxxxxx_xx": (
"xx:xxxxxxxxxxxxxxxxx_xxxxx_xxxxxxx_xxxxxxxxxxx{xx}xxx_xxxxx_xxxxxxxxx_xxxxxxxxxxxx_xxxx"
)
}
x = {
"xx_xxxxx_xxxxxxxxxx_xxxxxxxxx_xx": (
"xx:xxxxxxxxxxxxxxxxx_xxxxx_xxxxxxx_xxxxxxxxxxx{xx}xxx_xxxxx_xxxxxxxxx_xxxxxxxxxxxx_xxxx"
),
}
x = {
"foo": bar,
"foo": bar,
"foo": (
xx_xxxxxxxxxxxxxxxxx_xxxxx_xxxxxxx_xxxxxxxxxxxxxx_xxxxx_xxxxxxxxx_xxxxxxxxxxxx_xxxx
),
}
x = {
"xx_xxxxx_xxxxxxxxxx_xxxxxxxxx_xx": "xx:xxxxxxxxxxxxxxxxx_xxxxx_xxxxxxx_xxxxxxxxxx"
}
my_dict = {
"something_something": (
r"Lorem ipsum dolor sit amet, an sed convenire eloquentiam \t"
r"signiferumque, duo ea vocibus consetetur scriptorem. Facer \t"
r"signiferumque, duo ea vocibus consetetur scriptorem. Facer \t"
),
}
# Function calls as keys
tasks = {
get_key_name(
foo,
bar,
baz,
): src,
loop.run_in_executor(): src,
loop.run_in_executor(xx_xxxxxxxxxxxxxxxxx_xxxxx_xxxxxxx_xxxxxxxxxxxxxx): src,
loop.run_in_executor(
xx_xxxxxxxxxxxxxxxxx_xxxxx_xxxxxxx_xxxxxxxxxxxxxx_xxxxx_xxxxx
): src,
loop.run_in_executor(): (
xx_xxxxxxxxxxxxxxxxx_xxxxx_xxxxxxx_xxxxxxxxxxxxxx_xxxxx_xxxxxxxxx_xxxxxxxxxxxx_xxxx
),
}
# Dictionary comprehensions
tasks = {
key_name: (
xx_xxxxxxxxxxxxxxxxx_xxxxx_xxxxxxx_xxxxxxxxxxxxxx_xxxxx_xxxxxxxxx_xxxxxxxxxxxx_xxxx
)
for src in sources
}
tasks = {key_name: foobar for src in sources}
tasks = {
get_key_name(
src,
): "foo"
for src in sources
}
tasks = {
get_key_name(
foo,
bar,
baz,
): src
for src in sources
}
tasks = {
get_key_name(): (
xx_xxxxxxxxxxxxxxxxx_xxxxx_xxxxxxx_xxxxxxxxxxxxxx_xxxxx_xxxxxxxxx_xxxxxxxxxxxx_xxxx
)
for src in sources
}
tasks = {get_key_name(): foobar for src in sources}
# Delimiters inside the value
def foo():
def bar():
x = {
common.models.DateTimeField: (
datetime(2020, 1, 31, tzinfo=utc) + timedelta(days=i)
),
}
x = {
common.models.DateTimeField: (
datetime(2020, 1, 31, tzinfo=utc) + timedelta(days=i)
),
}
x = {
"foobar": 123 + 456,
}
x = {
"foobar": (123) + 456,
}
my_dict = {
"a key in my dict": (
a_very_long_variable * and_a_very_long_function_call() / 100000.0
)
}
my_dict = {
"a key in my dict": (
a_very_long_variable
* and_a_very_long_function_call()
* and_another_long_func()
/ 100000.0
)
}
my_dict = {
"a key in my dict": (
MyClass.some_attribute.first_call()
.second_call()
.third_call(some_args="some value")
)
}
{
"xxxxxx": xxxxxxxxxxxxxxxxxxx.xxxxxxxxxxxxxx(
xxxxxxxxxxxxxx={
"x": xxxxxxxxxxxxxxxxxxxxxxxxxx.xxxxxxxxxxxxxxxxxxxxxxxxxxxxx(
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx=(
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx(
xxxxxxxxxxxxx=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx(
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx={
"x": x.xx,
"x": x.x,
}
)
)
)
)
}
),
}
class Random:
def func():
random_service.status.active_states.inactive = make_new_top_level_state_from_dict(
{
"topLevelBase": {
"secondaryBase": {
"timestamp": 1234,
"latitude": 1,
"longitude": 2,
"actionTimestamp": (
Timestamp(seconds=1530584000, nanos=0).ToJsonString()
),
}
},
}
)
| python | MIT | c3cc5a95d4f72e6ccc27ebae23344fce8cc70786 | 2026-01-04T14:40:23.735327Z | false |
psf/black | https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/type_comment_syntax_error.py | tests/data/cases/type_comment_syntax_error.py | def foo(
# type: Foo
x): pass
# output
def foo(
# type: Foo
x,
):
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_39.py | tests/data/cases/context_managers_39.py | with \
make_context_manager1() as cm1, \
make_context_manager2() as cm2, \
make_context_manager3() as cm3, \
make_context_manager4() as cm4 \
:
pass
# Leading comment
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 (
new_new_new1() as cm1,
new_new_new2()
):
pass
# Leading comment.
with (
# First comment.
new_new_new1() as cm1,
# Second comment.
new_new_new2()
# Last comment.
):
pass
with \
this_is_a_very_long_call(looong_arg1=looong_value1, looong_arg2=looong_value2) as cm1, \
this_is_a_very_long_call(looong_arg1=looong_value1, looong_arg2=looong_value2, looong_arg3=looong_value3, looong_arg4=looong_value4) as cm2 \
:
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
with xxxxxxxx.some_kind_of_method(
some_argument=[
"first",
"second",
"third",
]
).another_method() as cmd:
pass
async def func():
async with \
make_context_manager1() as cm1, \
make_context_manager2() as cm2, \
make_context_manager3() as cm3, \
make_context_manager4() as cm4 \
:
pass
async with some_function(
argument1, argument2, argument3="some_value"
) as some_cm, some_other_function(
argument1, argument2, argument3="some_value"
):
pass
# don't remove the brackets here, it changes the meaning of the code.
with (x, y) as z:
pass
# output
with (
make_context_manager1() as cm1,
make_context_manager2() as cm2,
make_context_manager3() as cm3,
make_context_manager4() as cm4,
):
pass
# Leading comment
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 new_new_new1() as cm1, new_new_new2():
pass
# Leading comment.
with (
# First comment.
new_new_new1() as cm1,
# Second comment.
new_new_new2(),
# Last comment.
):
pass
with (
this_is_a_very_long_call(
looong_arg1=looong_value1, looong_arg2=looong_value2
) as cm1,
this_is_a_very_long_call(
looong_arg1=looong_value1,
looong_arg2=looong_value2,
looong_arg3=looong_value3,
looong_arg4=looong_value4,
) as cm2,
):
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
with xxxxxxxx.some_kind_of_method(
some_argument=[
"first",
"second",
"third",
]
).another_method() as cmd:
pass
async def func():
async with (
make_context_manager1() as cm1,
make_context_manager2() as cm2,
make_context_manager3() as cm3,
make_context_manager4() as cm4,
):
pass
async with (
some_function(argument1, argument2, argument3="some_value") as some_cm,
some_other_function(argument1, argument2, argument3="some_value"),
):
pass
# don't remove the brackets here, it changes the meaning of the code.
with (x, y) as z:
pass
| python | MIT | c3cc5a95d4f72e6ccc27ebae23344fce8cc70786 | 2026-01-04T14:40:23.735327Z | false |
psf/black | https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/line_ranges_unwrapping.py | tests/data/cases/line_ranges_unwrapping.py | # flags: --line-ranges=5-5 --line-ranges=9-9 --line-ranges=13-13
# NOTE: If you need to modify this file, pay special attention to the --line-ranges=
# flag above as it's formatting specifically these lines.
alist = [
1, 2
]
adict = {
"key" : "value"
}
func_call (
arg = value
)
# output
# flags: --line-ranges=5-5 --line-ranges=9-9 --line-ranges=13-13
# NOTE: If you need to modify this file, pay special attention to the --line-ranges=
# flag above as it's formatting specifically these lines.
alist = [1, 2]
adict = {"key": "value"}
func_call(arg=value)
| python | MIT | c3cc5a95d4f72e6ccc27ebae23344fce8cc70786 | 2026-01-04T14:40:23.735327Z | false |
psf/black | https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/power_op_spacing_long.py | tests/data/cases/power_op_spacing_long.py | a = 1**1**1**1**1**1**1**1**1**1**1**1**1**1**1**1**1**1**1**1**1**1**1**1**1**1**1**1
b = 1**1**1**1**1**1**1**1**1**1**1**1**1**1**1**1**1**1**1**1**1**1**1**1**1**1**1**1**1
c = 1 ** 1 ** 1 ** 1 ** 1 ** 1 ** 1 ** 1 ** 1 ** 1 ** 1 ** 1 ** 1 ** 1 ** 1 ** 1 ** 1 ** 1 ** 1 ** 1 ** 1 ** 1 ** 1 ** 1 ** 1 ** 1 ** 1 ** 1
d = 1**1 ** 1**1 ** 1**1 ** 1**1 ** 1**1**1 ** 1 ** 1**1 ** 1**1**1**1**1 ** 1 ** 1**1**1 **1**1** 1 ** 1 ** 1
e = 𨉟**𨉟**𨉟**𨉟**𨉟**𨉟**𨉟**𨉟**𨉟**𨉟**𨉟**𨉟**𨉟**𨉟**𨉟**𨉟**𨉟**𨉟**𨉟**𨉟**𨉟
f = 𨉟**𨉟**𨉟**𨉟**𨉟**𨉟**𨉟**𨉟**𨉟**𨉟**𨉟**𨉟**𨉟**𨉟**𨉟**𨉟**𨉟**𨉟**𨉟**𨉟**𨉟**𨉟
a = 1.0**1.0**1.0**1.0**1.0**1.0**1.0**1.0**1.0**1.0**1.0**1.0**1.0**1.0**1.0**1.0**1.0
b = 1.0**1.0**1.0**1.0**1.0**1.0**1.0**1.0**1.0**1.0**1.0**1.0**1.0**1.0**1.0**1.0**1.0**1.0
c = 1.0 ** 1.0 ** 1.0 ** 1.0 ** 1.0 ** 1.0 ** 1.0 ** 1.0 ** 1.0 ** 1.0 ** 1.0 ** 1.0 ** 1.0 ** 1.0 ** 1.0 ** 1.0 ** 1.0
d = 1.0**1.0 ** 1.0**1.0 ** 1.0**1.0 ** 1.0**1.0 ** 1.0**1.0**1.0 ** 1.0 ** 1.0**1.0 ** 1.0**1.0**1.0
# output
a = 1**1**1**1**1**1**1**1**1**1**1**1**1**1**1**1**1**1**1**1**1**1**1**1**1**1**1**1
b = (
1
** 1
** 1
** 1
** 1
** 1
** 1
** 1
** 1
** 1
** 1
** 1
** 1
** 1
** 1
** 1
** 1
** 1
** 1
** 1
** 1
** 1
** 1
** 1
** 1
** 1
** 1
** 1
** 1
)
c = 1**1**1**1**1**1**1**1**1**1**1**1**1**1**1**1**1**1**1**1**1**1**1**1**1**1**1**1
d = 1**1**1**1**1**1**1**1**1**1**1**1**1**1**1**1**1**1**1**1**1**1**1**1**1**1**1**1
e = 𨉟**𨉟**𨉟**𨉟**𨉟**𨉟**𨉟**𨉟**𨉟**𨉟**𨉟**𨉟**𨉟**𨉟**𨉟**𨉟**𨉟**𨉟**𨉟**𨉟**𨉟
f = (
𨉟
** 𨉟
** 𨉟
** 𨉟
** 𨉟
** 𨉟
** 𨉟
** 𨉟
** 𨉟
** 𨉟
** 𨉟
** 𨉟
** 𨉟
** 𨉟
** 𨉟
** 𨉟
** 𨉟
** 𨉟
** 𨉟
** 𨉟
** 𨉟
** 𨉟
)
a = 1.0**1.0**1.0**1.0**1.0**1.0**1.0**1.0**1.0**1.0**1.0**1.0**1.0**1.0**1.0**1.0**1.0
b = (
1.0
** 1.0
** 1.0
** 1.0
** 1.0
** 1.0
** 1.0
** 1.0
** 1.0
** 1.0
** 1.0
** 1.0
** 1.0
** 1.0
** 1.0
** 1.0
** 1.0
** 1.0
)
c = 1.0**1.0**1.0**1.0**1.0**1.0**1.0**1.0**1.0**1.0**1.0**1.0**1.0**1.0**1.0**1.0**1.0
d = 1.0**1.0**1.0**1.0**1.0**1.0**1.0**1.0**1.0**1.0**1.0**1.0**1.0**1.0**1.0**1.0**1.0
| python | MIT | c3cc5a95d4f72e6ccc27ebae23344fce8cc70786 | 2026-01-04T14:40:23.735327Z | false |
psf/black | https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/expression.py | tests/data/cases/expression.py | ...
'some_string'
b'\\xa3'
Name
None
True
False
1
1.0
1j
True or False
True or False or None
True and False
True and False and None
(Name1 and Name2) or Name3
Name1 and Name2 or Name3
Name1 or (Name2 and Name3)
Name1 or Name2 and Name3
(Name1 and Name2) or (Name3 and Name4)
Name1 and Name2 or Name3 and Name4
Name1 or (Name2 and Name3) or Name4
Name1 or Name2 and Name3 or Name4
v1 << 2
1 >> v2
1 % finished
1 + v2 - v3 * 4 ^ 5 ** v6 / 7 // 8
((1 + v2) - (v3 * 4)) ^ (((5 ** v6) / 7) // 8)
not great
~great
+value
-1
~int and not v1 ^ 123 + v2 | True
(~int) and (not ((v1 ^ (123 + v2)) | True))
+really ** -confusing ** ~operator ** -precedence
flags & ~ select.EPOLLIN and waiters.write_task is not None
lambda arg: None
lambda a=True: a
lambda a, b, c=True: a
lambda a, b, c=True, *, d=(1 << v2), e='str': a
lambda a, b, c=True, *vararg, d=(v1 << 2), e='str', **kwargs: a + b
manylambdas = lambda x=lambda y=lambda z=1: z: y(): x()
foo = (lambda port_id, ignore_missing: {"port1": port1_resource, "port2": port2_resource}[port_id])
1 if True else 2
str or None if True else str or bytes or None
(str or None) if True else (str or bytes or None)
str or None if (1 if True else 2) else str or bytes or None
(str or None) if (1 if True else 2) else (str or bytes or None)
((super_long_variable_name or None) if (1 if super_long_test_name else 2) else (str or bytes or None))
{'2.7': dead, '3.7': (long_live or die_hard)}
{'2.7': dead, '3.7': (long_live or die_hard), **{'3.6': verygood}}
{**a, **b, **c}
{'2.7', '3.6', '3.7', '3.8', '3.9', ('4.0' if gilectomy else '3.10')}
({'a': 'b'}, (True or False), (+value), 'string', b'bytes') or None
()
(1,)
(1, 2)
(1, 2, 3)
[]
[1, 2, 3, 4, 5, 6, 7, 8, 9, (10 or A), (11 or B), (12 or C)]
[1, 2, 3,]
[*a]
[*range(10)]
[*a, 4, 5,]
[4, *a, 5,]
[this_is_a_very_long_variable_which_will_force_a_delimiter_split, element, another, *more]
{i for i in (1, 2, 3)}
{(i ** 2) for i in (1, 2, 3)}
{(i ** 2) for i, _ in ((1, 'a'), (2, 'b'), (3, 'c'))}
{((i ** 2) + j) for i in (1, 2, 3) for j in (1, 2, 3)}
[i for i in (1, 2, 3)]
[(i ** 2) for i in (1, 2, 3)]
[(i ** 2) for i, _ in ((1, 'a'), (2, 'b'), (3, 'c'))]
[((i ** 2) + j) for i in (1, 2, 3) for j in (1, 2, 3)]
{i: 0 for i in (1, 2, 3)}
{i: j for i, j in ((1, 'a'), (2, 'b'), (3, 'c'))}
{a: b * 2 for a, b in dictionary.items()}
{a: b * -2 for a, b in dictionary.items()}
{k: v for k, v in this_is_a_very_long_variable_which_will_cause_a_trailing_comma_which_breaks_the_comprehension}
Python3 > Python2 > COBOL
Life is Life
call()
call(arg)
call(kwarg='hey')
call(arg, kwarg='hey')
call(arg, another, kwarg='hey', **kwargs)
call(this_is_a_very_long_variable_which_will_force_a_delimiter_split, arg, another, kwarg='hey', **kwargs) # note: no trailing comma pre-3.6
call(*gidgets[:2])
call(a, *gidgets[:2])
call(**self.screen_kwargs)
call(b, **self.screen_kwargs)
lukasz.langa.pl
call.me(maybe)
1 .real
1.0 .real
....__class__
list[str]
dict[str, int]
tuple[str, ...]
tuple[
str, int, float, dict[str, int]
]
tuple[str, int, float, dict[str, int],]
very_long_variable_name_filters: t.List[
t.Tuple[str, t.Union[str, t.List[t.Optional[str]]]],
]
xxxx_xxxxx_xxxx_xxx: Callable[..., List[SomeClass]] = classmethod( # type: ignore
sync(async_xxxx_xxx_xxxx_xxxxx_xxxx_xxx.__func__)
)
xxxx_xxx_xxxx_xxxxx_xxxx_xxx: Callable[..., List[SomeClass]] = classmethod( # type: ignore
sync(async_xxxx_xxx_xxxx_xxxxx_xxxx_xxx.__func__)
)
xxxx_xxx_xxxx_xxxxx_xxxx_xxx: Callable[
..., List[SomeClass]
] = classmethod(sync(async_xxxx_xxx_xxxx_xxxxx_xxxx_xxx.__func__)) # type: ignore
slice[0]
slice[0:1]
slice[0:1:2]
slice[:]
slice[:-1]
slice[1:]
slice[::-1]
slice[d :: d + 1]
slice[:c, c - 1]
numpy[:, 0:1]
numpy[:, :-1]
numpy[0, :]
numpy[:, i]
numpy[0, :2]
numpy[:N, 0]
numpy[:2, :4]
numpy[2:4, 1:5]
numpy[4:, 2:]
numpy[:, (0, 1, 2, 5)]
numpy[0, [0]]
numpy[:, [i]]
numpy[1 : c + 1, c]
numpy[-(c + 1) :, d]
numpy[:, l[-2]]
numpy[:, ::-1]
numpy[np.newaxis, :]
(str or None) if (sys.version_info[0] > (3,)) else (str or bytes or None)
{'2.7': dead, '3.7': long_live or die_hard}
{'2.7', '3.6', '3.7', '3.8', '3.9', '4.0' if gilectomy else '3.10'}
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10 or A, 11 or B, 12 or C]
(SomeName)
SomeName
(Good, Bad, Ugly)
(i for i in (1, 2, 3))
((i ** 2) for i in (1, 2, 3))
((i ** 2) for i, _ in ((1, 'a'), (2, 'b'), (3, 'c')))
(((i ** 2) + j) for i in (1, 2, 3) for j in (1, 2, 3))
(*starred,)
{"id": "1","type": "type","started_at": now(),"ended_at": now() + timedelta(days=10),"priority": 1,"import_session_id": 1,**kwargs}
a = (1,)
b = 1,
c = 1
d = (1,) + a + (2,)
e = (1,).count(1)
f = 1, *range(10)
g = 1, *"ten"
what_is_up_with_those_new_coord_names = (coord_names + set(vars_to_create)) + set(vars_to_remove)
what_is_up_with_those_new_coord_names = (coord_names | set(vars_to_create)) - set(vars_to_remove)
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()
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()
Ø = set()
authors.łukasz.say_thanks()
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 gen():
yield from outside_of_generator
a = (yield)
b = ((yield))
c = (((yield)))
async def f():
await some.complicated[0].call(with_args=(True or (1 is not 1)))
print(* [] or [1])
print(**{1: 3} if False else {x: x for x in range(3)})
print(* lambda x: x)
assert(not Test),("Short message")
assert this is ComplexTest and not requirements.fit_in_a_single_line(force=False), "Short message"
assert(((parens is TooMany)))
for x, in (1,), (2,), (3,): ...
for y in (): ...
for z in (i for i in (1, 2, 3)): ...
for i in (call()): ...
for j in (1 + (2 + 3)): ...
while(this and that): ...
for addr_family, addr_type, addr_proto, addr_canonname, addr_sockaddr in socket.getaddrinfo('google.com', 'http'):
pass
a = aaaa.bbbb.cccc.dddd.eeee.ffff.gggg.hhhh.iiii.jjjj.kkkk.llll.mmmm.nnnn.oooo.pppp in qqqq.rrrr.ssss.tttt.uuuu.vvvv.xxxx.yyyy.zzzz
a = aaaa.bbbb.cccc.dddd.eeee.ffff.gggg.hhhh.iiii.jjjj.kkkk.llll.mmmm.nnnn.oooo.pppp not in qqqq.rrrr.ssss.tttt.uuuu.vvvv.xxxx.yyyy.zzzz
a = aaaa.bbbb.cccc.dddd.eeee.ffff.gggg.hhhh.iiii.jjjj.kkkk.llll.mmmm.nnnn.oooo.pppp is qqqq.rrrr.ssss.tttt.uuuu.vvvv.xxxx.yyyy.zzzz
a = aaaa.bbbb.cccc.dddd.eeee.ffff.gggg.hhhh.iiii.jjjj.kkkk.llll.mmmm.nnnn.oooo.pppp is not qqqq.rrrr.ssss.tttt.uuuu.vvvv.xxxx.yyyy.zzzz
if (
threading.current_thread() != threading.main_thread() and
threading.current_thread() != threading.main_thread() or
signal.getsignal(signal.SIGINT) != signal.default_int_handler
):
return True
if (
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa |
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
):
return True
if (
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa &
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
):
return True
if (
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
):
return True
if (
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
):
return True
if (
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
):
return True
if (
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa /
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
):
return True
if (
~ aaaa.a + aaaa.b - aaaa.c * aaaa.d / aaaa.e | aaaa.f & aaaa.g % aaaa.h ^ aaaa.i << aaaa.k >> aaaa.l ** aaaa.m // aaaa.n
):
return True
if (
~ aaaaaaaa.a + aaaaaaaa.b - aaaaaaaa.c @ aaaaaaaa.d / aaaaaaaa.e | aaaaaaaa.f & aaaaaaaa.g % aaaaaaaa.h ^ aaaaaaaa.i << aaaaaaaa.k >> aaaaaaaa.l ** aaaaaaaa.m // aaaaaaaa.n
):
return True
if (
~ aaaaaaaaaaaaaaaa.a + aaaaaaaaaaaaaaaa.b - aaaaaaaaaaaaaaaa.c * aaaaaaaaaaaaaaaa.d @ aaaaaaaaaaaaaaaa.e | aaaaaaaaaaaaaaaa.f & aaaaaaaaaaaaaaaa.g % aaaaaaaaaaaaaaaa.h ^ aaaaaaaaaaaaaaaa.i << aaaaaaaaaaaaaaaa.k >> aaaaaaaaaaaaaaaa.l ** aaaaaaaaaaaaaaaa.m // aaaaaaaaaaaaaaaa.n
):
return True
aaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaa - aaaaaaaaaaaaaaaa * (aaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaa) / (aaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaa)
aaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
bbbb >> bbbb * bbbb
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ^bbbb.a & aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa^aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
last_call()
# standalone comment at ENDMARKER
# output
...
"some_string"
b"\\xa3"
Name
None
True
False
1
1.0
1j
True or False
True or False or None
True and False
True and False and None
(Name1 and Name2) or Name3
Name1 and Name2 or Name3
Name1 or (Name2 and Name3)
Name1 or Name2 and Name3
(Name1 and Name2) or (Name3 and Name4)
Name1 and Name2 or Name3 and Name4
Name1 or (Name2 and Name3) or Name4
Name1 or Name2 and Name3 or Name4
v1 << 2
1 >> v2
1 % finished
1 + v2 - v3 * 4 ^ 5**v6 / 7 // 8
((1 + v2) - (v3 * 4)) ^ (((5**v6) / 7) // 8)
not great
~great
+value
-1
~int and not v1 ^ 123 + v2 | True
(~int) and (not ((v1 ^ (123 + v2)) | True))
+(really ** -(confusing ** ~(operator**-precedence)))
flags & ~select.EPOLLIN and waiters.write_task is not None
lambda arg: None
lambda a=True: a
lambda a, b, c=True: a
lambda a, b, c=True, *, d=(1 << v2), e="str": a
lambda a, b, c=True, *vararg, d=(v1 << 2), e="str", **kwargs: a + b
manylambdas = lambda x=lambda y=lambda z=1: z: y(): x()
foo = lambda port_id, ignore_missing: {
"port1": port1_resource,
"port2": port2_resource,
}[port_id]
1 if True else 2
str or None if True else str or bytes or None
(str or None) if True else (str or bytes or None)
str or None if (1 if True else 2) else str or bytes or None
(str or None) if (1 if True else 2) else (str or bytes or None)
(
(super_long_variable_name or None)
if (1 if super_long_test_name else 2)
else (str or bytes or None)
)
{"2.7": dead, "3.7": (long_live or die_hard)}
{"2.7": dead, "3.7": (long_live or die_hard), **{"3.6": verygood}}
{**a, **b, **c}
{"2.7", "3.6", "3.7", "3.8", "3.9", ("4.0" if gilectomy else "3.10")}
({"a": "b"}, (True or False), (+value), "string", b"bytes") or None
()
(1,)
(1, 2)
(1, 2, 3)
[]
[1, 2, 3, 4, 5, 6, 7, 8, 9, (10 or A), (11 or B), (12 or C)]
[
1,
2,
3,
]
[*a]
[*range(10)]
[
*a,
4,
5,
]
[
4,
*a,
5,
]
[
this_is_a_very_long_variable_which_will_force_a_delimiter_split,
element,
another,
*more,
]
{i for i in (1, 2, 3)}
{(i**2) for i in (1, 2, 3)}
{(i**2) for i, _ in ((1, "a"), (2, "b"), (3, "c"))}
{((i**2) + j) for i in (1, 2, 3) for j in (1, 2, 3)}
[i for i in (1, 2, 3)]
[(i**2) for i in (1, 2, 3)]
[(i**2) for i, _ in ((1, "a"), (2, "b"), (3, "c"))]
[((i**2) + j) for i in (1, 2, 3) for j in (1, 2, 3)]
{i: 0 for i in (1, 2, 3)}
{i: j for i, j in ((1, "a"), (2, "b"), (3, "c"))}
{a: b * 2 for a, b in dictionary.items()}
{a: b * -2 for a, b in dictionary.items()}
{
k: v
for k, v in this_is_a_very_long_variable_which_will_cause_a_trailing_comma_which_breaks_the_comprehension
}
Python3 > Python2 > COBOL
Life is Life
call()
call(arg)
call(kwarg="hey")
call(arg, kwarg="hey")
call(arg, another, kwarg="hey", **kwargs)
call(
this_is_a_very_long_variable_which_will_force_a_delimiter_split,
arg,
another,
kwarg="hey",
**kwargs
) # note: no trailing comma pre-3.6
call(*gidgets[:2])
call(a, *gidgets[:2])
call(**self.screen_kwargs)
call(b, **self.screen_kwargs)
lukasz.langa.pl
call.me(maybe)
(1).real
(1.0).real
....__class__
list[str]
dict[str, int]
tuple[str, ...]
tuple[str, int, float, dict[str, int]]
tuple[
str,
int,
float,
dict[str, int],
]
very_long_variable_name_filters: t.List[
t.Tuple[str, t.Union[str, t.List[t.Optional[str]]]],
]
xxxx_xxxxx_xxxx_xxx: Callable[..., List[SomeClass]] = classmethod( # type: ignore
sync(async_xxxx_xxx_xxxx_xxxxx_xxxx_xxx.__func__)
)
xxxx_xxx_xxxx_xxxxx_xxxx_xxx: Callable[..., List[SomeClass]] = classmethod( # type: ignore
sync(async_xxxx_xxx_xxxx_xxxxx_xxxx_xxx.__func__)
)
xxxx_xxx_xxxx_xxxxx_xxxx_xxx: Callable[..., List[SomeClass]] = classmethod(
sync(async_xxxx_xxx_xxxx_xxxxx_xxxx_xxx.__func__)
) # type: ignore
slice[0]
slice[0:1]
slice[0:1:2]
slice[:]
slice[:-1]
slice[1:]
slice[::-1]
slice[d :: d + 1]
slice[:c, c - 1]
numpy[:, 0:1]
numpy[:, :-1]
numpy[0, :]
numpy[:, i]
numpy[0, :2]
numpy[:N, 0]
numpy[:2, :4]
numpy[2:4, 1:5]
numpy[4:, 2:]
numpy[:, (0, 1, 2, 5)]
numpy[0, [0]]
numpy[:, [i]]
numpy[1 : c + 1, c]
numpy[-(c + 1) :, d]
numpy[:, l[-2]]
numpy[:, ::-1]
numpy[np.newaxis, :]
(str or None) if (sys.version_info[0] > (3,)) else (str or bytes or None)
{"2.7": dead, "3.7": long_live or die_hard}
{"2.7", "3.6", "3.7", "3.8", "3.9", "4.0" if gilectomy else "3.10"}
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10 or A, 11 or B, 12 or C]
(SomeName)
SomeName
(Good, Bad, Ugly)
(i for i in (1, 2, 3))
((i**2) for i in (1, 2, 3))
((i**2) for i, _ in ((1, "a"), (2, "b"), (3, "c")))
(((i**2) + j) for i in (1, 2, 3) for j in (1, 2, 3))
(*starred,)
{
"id": "1",
"type": "type",
"started_at": now(),
"ended_at": now() + timedelta(days=10),
"priority": 1,
"import_session_id": 1,
**kwargs,
}
a = (1,)
b = (1,)
c = 1
d = (1,) + a + (2,)
e = (1,).count(1)
f = 1, *range(10)
g = 1, *"ten"
what_is_up_with_those_new_coord_names = (coord_names + set(vars_to_create)) + set(
vars_to_remove
)
what_is_up_with_those_new_coord_names = (coord_names | set(vars_to_create)) - set(
vars_to_remove
)
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()
)
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()
)
Ø = set()
authors.łukasz.say_thanks()
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 gen():
yield from outside_of_generator
a = yield
b = yield
c = yield
async def f():
await some.complicated[0].call(with_args=(True or (1 is not 1)))
print(*[] or [1])
print(**{1: 3} if False else {x: x for x in range(3)})
print(*lambda x: x)
assert not Test, "Short message"
assert this is ComplexTest and not requirements.fit_in_a_single_line(
force=False
), "Short message"
assert parens is TooMany
for (x,) in (1,), (2,), (3,):
...
for y in ():
...
for z in (i for i in (1, 2, 3)):
...
for i in call():
...
for j in 1 + (2 + 3):
...
while this and that:
...
for (
addr_family,
addr_type,
addr_proto,
addr_canonname,
addr_sockaddr,
) in socket.getaddrinfo("google.com", "http"):
pass
a = (
aaaa.bbbb.cccc.dddd.eeee.ffff.gggg.hhhh.iiii.jjjj.kkkk.llll.mmmm.nnnn.oooo.pppp
in qqqq.rrrr.ssss.tttt.uuuu.vvvv.xxxx.yyyy.zzzz
)
a = (
aaaa.bbbb.cccc.dddd.eeee.ffff.gggg.hhhh.iiii.jjjj.kkkk.llll.mmmm.nnnn.oooo.pppp
not in qqqq.rrrr.ssss.tttt.uuuu.vvvv.xxxx.yyyy.zzzz
)
a = (
aaaa.bbbb.cccc.dddd.eeee.ffff.gggg.hhhh.iiii.jjjj.kkkk.llll.mmmm.nnnn.oooo.pppp
is qqqq.rrrr.ssss.tttt.uuuu.vvvv.xxxx.yyyy.zzzz
)
a = (
aaaa.bbbb.cccc.dddd.eeee.ffff.gggg.hhhh.iiii.jjjj.kkkk.llll.mmmm.nnnn.oooo.pppp
is not qqqq.rrrr.ssss.tttt.uuuu.vvvv.xxxx.yyyy.zzzz
)
if (
threading.current_thread() != threading.main_thread()
and threading.current_thread() != threading.main_thread()
or signal.getsignal(signal.SIGINT) != signal.default_int_handler
):
return True
if (
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
| aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
):
return True
if (
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
& aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
):
return True
if (
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
+ aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
):
return True
if (
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
- aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
):
return True
if (
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
* aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
):
return True
if (
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
/ aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
):
return True
if (
~aaaa.a + aaaa.b - aaaa.c * aaaa.d / aaaa.e
| aaaa.f & aaaa.g % aaaa.h ^ aaaa.i << aaaa.k >> aaaa.l**aaaa.m // aaaa.n
):
return True
if (
~aaaaaaaa.a + aaaaaaaa.b - aaaaaaaa.c @ aaaaaaaa.d / aaaaaaaa.e
| aaaaaaaa.f & aaaaaaaa.g % aaaaaaaa.h
^ aaaaaaaa.i << aaaaaaaa.k >> aaaaaaaa.l**aaaaaaaa.m // aaaaaaaa.n
):
return True
if (
~aaaaaaaaaaaaaaaa.a
+ aaaaaaaaaaaaaaaa.b
- aaaaaaaaaaaaaaaa.c * aaaaaaaaaaaaaaaa.d @ aaaaaaaaaaaaaaaa.e
| aaaaaaaaaaaaaaaa.f & aaaaaaaaaaaaaaaa.g % aaaaaaaaaaaaaaaa.h
^ aaaaaaaaaaaaaaaa.i
<< aaaaaaaaaaaaaaaa.k
>> aaaaaaaaaaaaaaaa.l**aaaaaaaaaaaaaaaa.m // aaaaaaaaaaaaaaaa.n
):
return True
(
aaaaaaaaaaaaaaaa
+ aaaaaaaaaaaaaaaa
- aaaaaaaaaaaaaaaa
* (aaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaa)
/ (aaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaa)
)
aaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaa
(
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
>> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
<< aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
)
bbbb >> bbbb * bbbb
(
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
^ bbbb.a & aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
^ aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
)
last_call()
# standalone comment at ENDMARKER
| python | MIT | c3cc5a95d4f72e6ccc27ebae23344fce8cc70786 | 2026-01-04T14:40:23.735327Z | false |
psf/black | https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/fmtskip10.py | tests/data/cases/fmtskip10.py | # flags: --preview
def foo(): return "mock" # fmt: skip
if True: print("yay") # fmt: skip
for i in range(10): print(i) # fmt: skip
if True: print("this"); print("that") # fmt: skip
while True: print("loop"); break # fmt: skip
for x in [1, 2]: print(x); print("done") # fmt: skip
def f(x: int): return x # fmt: skip
j = 1 # fmt: skip
while j < 10: j += 1 # fmt: skip
b = [c for c in "A very long string that would normally generate some kind of collapse, since it is this long"] # fmt: skip
v = (
foo_dict # fmt: skip
.setdefault("a", {})
.setdefault("b", {})
.setdefault("c", {})
.setdefault("d", {})
.setdefault("e", {})
)
| python | MIT | c3cc5a95d4f72e6ccc27ebae23344fce8cc70786 | 2026-01-04T14:40:23.735327Z | false |
psf/black | https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/stub.py | tests/data/cases/stub.py | # flags: --pyi
X: int
def f(): ...
class D:
...
class C:
...
class B:
this_lack_of_newline_should_be_kept: int
def b(self) -> None: ...
but_this_newline_should_also_be_kept: int
class A:
attr: int
attr2: str
def f(self) -> int:
...
def g(self) -> str: ...
def g():
...
def h(): ...
if sys.version_info >= (3, 8):
class E:
def f(self): ...
class F:
def f(self): ...
class G: ...
class H: ...
else:
class I: ...
class J: ...
def f(): ...
class K:
def f(self): ...
def f(): ...
class Nested:
class dirty: ...
class little: ...
class secret:
def who_has_to_know(self): ...
def verse(self): ...
class Conditional:
def f(self): ...
if sys.version_info >= (3, 8):
def g(self): ...
else:
def g(self): ...
def h(self): ...
def i(self): ...
if sys.version_info >= (3, 8):
def j(self): ...
def k(self): ...
if sys.version_info >= (3, 8):
class A: ...
class B: ...
class C:
def l(self): ...
def m(self): ...
# output
X: int
def f(): ...
class D: ...
class C: ...
class B:
this_lack_of_newline_should_be_kept: int
def b(self) -> None: ...
but_this_newline_should_also_be_kept: int
class A:
attr: int
attr2: str
def f(self) -> int: ...
def g(self) -> str: ...
def g(): ...
def h(): ...
if sys.version_info >= (3, 8):
class E:
def f(self): ...
class F:
def f(self): ...
class G: ...
class H: ...
else:
class I: ...
class J: ...
def f(): ...
class K:
def f(self): ...
def f(): ...
class Nested:
class dirty: ...
class little: ...
class secret:
def who_has_to_know(self): ...
def verse(self): ...
class Conditional:
def f(self): ...
if sys.version_info >= (3, 8):
def g(self): ...
else:
def g(self): ...
def h(self): ...
def i(self): ...
if sys.version_info >= (3, 8):
def j(self): ...
def k(self): ...
if sys.version_info >= (3, 8):
class A: ...
class B: ...
class C:
def l(self): ...
def m(self): ...
| python | MIT | c3cc5a95d4f72e6ccc27ebae23344fce8cc70786 | 2026-01-04T14:40:23.735327Z | false |
psf/black | https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/fmtonoff4.py | tests/data/cases/fmtonoff4.py | # fmt: off
@test([
1, 2,
3, 4,
])
# fmt: on
def f(): pass
@test([
1, 2,
3, 4,
])
def f(): pass
# output
# fmt: off
@test([
1, 2,
3, 4,
])
# fmt: on
def f():
pass
@test(
[
1,
2,
3,
4,
]
)
def f():
pass
| python | MIT | c3cc5a95d4f72e6ccc27ebae23344fce8cc70786 | 2026-01-04T14:40:23.735327Z | false |
psf/black | https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/fstring_quotations.py | tests/data/cases/fstring_quotations.py | # Regression tests for long f-strings, including examples from issue #3623
a = (
'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
f'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"{"b"}"'
)
a = (
f'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"{"b"}"'
'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
)
a = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + \
f'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"{"b"}"'
a = f'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"{"b"}"' + \
f'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"{"b"}"'
a = (
f'bbbbbbb"{"b"}"'
'aaaaaaaa'
)
a = (
f'"{"b"}"'
)
a = (
f'\"{"b"}\"'
)
a = (
r'\"{"b"}\"'
)
# output
# Regression tests for long f-strings, including examples from issue #3623
a = (
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
f'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"{"b"}"'
)
a = (
f'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"{"b"}"'
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
)
a = (
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
+ f'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"{"b"}"'
)
a = (
f'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"{"b"}"'
+ f'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"{"b"}"'
)
a = f'bbbbbbb"{"b"}"' "aaaaaaaa"
a = f'"{"b"}"'
a = f'"{"b"}"'
a = r'\"{"b"}\"'
| python | MIT | c3cc5a95d4f72e6ccc27ebae23344fce8cc70786 | 2026-01-04T14:40:23.735327Z | false |
psf/black | https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/pattern_matching_trailing_comma.py | tests/data/cases/pattern_matching_trailing_comma.py | # flags: --minimum-version=3.10
match maybe, multiple:
case perhaps, 5:
pass
case perhaps, 6,:
pass
match more := (than, one), indeed,:
case _, (5, 6):
pass
case [[5], (6)], [7],:
pass
case _:
pass
# output
match maybe, multiple:
case perhaps, 5:
pass
case (
perhaps,
6,
):
pass
match more := (than, one), indeed,:
case _, (5, 6):
pass
case (
[[5], (6)],
[7],
):
pass
case _:
pass | python | MIT | c3cc5a95d4f72e6ccc27ebae23344fce8cc70786 | 2026-01-04T14:40:23.735327Z | false |
psf/black | https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/single_line_format_skip_with_multiple_comments.py | tests/data/cases/single_line_format_skip_with_multiple_comments.py | foo = 123 # fmt: skip # noqa: E501 # pylint
bar = (
123 ,
( 1 + 5 ) # pylint # fmt:skip
)
baz = "a" + "b" # pylint; fmt: skip; noqa: E501
skip_will_not_work = "a" + "b" # pylint fmt:skip
skip_will_not_work2 = "a" + "b" # some text; fmt:skip happens to be part of it
# output
foo = 123 # fmt: skip # noqa: E501 # pylint
bar = (
123 ,
( 1 + 5 ) # pylint # fmt:skip
)
baz = "a" + "b" # pylint; fmt: skip; noqa: E501
skip_will_not_work = "a" + "b" # pylint fmt:skip
skip_will_not_work2 = "a" + "b" # some text; fmt:skip happens to be part of it
| 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__edge_case.py | tests/data/cases/preview_long_strings__edge_case.py | # flags: --unstable
some_variable = "This string is long but not so long that it needs to be split just yet"
some_variable = 'This string is long but not so long that it needs to be split just yet'
some_variable = "This string is long, just long enough that it needs to be split, u get?"
some_variable = 'This string is long, just long enough that it needs to be split, u get?'
some_variable = "This string is long, just long enough that it needs to be split, u get? So we stay"
some_variable = 'This string is long, just long enough that it needs to be split, u get? So we stay'
some_variable = "This string is long, just long enough that it needs to be split, u get? So we split"
some_variable = 'This string is long, just long enough that it needs to be split, u get? So we split'
some_variable = "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 alll".format("ha")
some_variable = "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 allll".format("ha")
some_variable = "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 alllllllllll".format("ha")
some_variable = "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")
some_variable = "This is a long string that will end with a method that is not calleddd".format
addition_inside_tuple = (
some_string_inside_a_variable
+ "Some string that is just long enough to cause a split to take place.............",
xyz,
"Some really long string that needs to get split eventually but I'm running out of things to say" + some_string_inside_a_variable
)
addition_inside_tuple = (
some_string_inside_a_variable
+ "Some string that is just long enough to cause a split to take place.............."
)
return "Hi there. This is areally really reallllly long string that needs to be split!!!"
ternary_expression = (
"Short String"
if some_condition
else "This is a really long string that will eventually need to be split right here."
)
return f'{x}/b/c/d/d/d/dadfjsadjsaidoaisjdsfjaofjdfijaidfjaodfjaoifjodjafojdoajaaaaaaaaaaa'
return f'{x}/b/c/d/d/d/dadfjsadjsaidoaisjdsfjaofjdfijaidfjaodfjaoifjodjafojdoajaaaaaaaaaaaa'
assert str(result) == "This long string should be split at some point right close to or around hereeeeeee"
assert str(result) < "This long string should be split at some point right close to or around hereeeeee"
assert "A format string: %s" % "This long string should be split at some point right close to or around hereeeeeee" != result
msg += "This long string should be wrapped in parens at some point right around hereeeee"
msg += "This long string should be split at some point right close to or around hereeeeeeee"
msg += "This long string should not be split at any point ever since it is just righttt"
# output
some_variable = "This string is long but not so long that it needs to be split just yet"
some_variable = "This string is long but not so long that it needs to be split just yet"
some_variable = (
"This string is long, just long enough that it needs to be split, u get?"
)
some_variable = (
"This string is long, just long enough that it needs to be split, u get?"
)
some_variable = (
"This string is long, just long enough that it needs to be split, u get? So we stay"
)
some_variable = (
"This string is long, just long enough that it needs to be split, u get? So we stay"
)
some_variable = (
"This string is long, just long enough that it needs to be split, u get? So we"
" split"
)
some_variable = (
"This string is long, just long enough that it needs to be split, u get? So we"
" split"
)
some_variable = (
"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 alll".format(
"ha"
)
)
some_variable = (
"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 allll"
.format("ha")
)
some_variable = (
"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 alllllllllll"
.format("ha")
)
some_variable = (
"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")
)
some_variable = (
"This is a long string that will end with a method that is not calleddd".format
)
addition_inside_tuple = (
some_string_inside_a_variable
+ "Some string that is just long enough to cause a split to take"
" place.............",
xyz,
"Some really long string that needs to get split eventually but I'm running out of"
" things to say"
+ some_string_inside_a_variable,
)
addition_inside_tuple = (
some_string_inside_a_variable
+ "Some string that is just long enough to cause a split to take"
" place.............."
)
return (
"Hi there. This is areally really reallllly long string that needs to be split!!!"
)
ternary_expression = (
"Short String"
if some_condition
else (
"This is a really long string that will eventually need to be split right here."
)
)
return (
f"{x}/b/c/d/d/d/dadfjsadjsaidoaisjdsfjaofjdfijaidfjaodfjaoifjodjafojdoajaaaaaaaaaaa"
)
return f"{x}/b/c/d/d/d/dadfjsadjsaidoaisjdsfjaofjdfijaidfjaodfjaoifjodjafojdoajaaaaaaaaaaaa"
assert (
str(result)
== "This long string should be split at some point right close to or around"
" hereeeeeee"
)
assert (
str(result)
< "This long string should be split at some point right close to or around"
" hereeeeee"
)
assert (
"A format string: %s"
% "This long string should be split at some point right close to or around"
" hereeeeeee"
!= result
)
msg += (
"This long string should be wrapped in parens at some point right around hereeeee"
)
msg += (
"This long string should be split at some point right close to or around"
" hereeeeeeee"
)
msg += "This long string should not be split at any point ever since it is just righttt"
| python | MIT | c3cc5a95d4f72e6ccc27ebae23344fce8cc70786 | 2026-01-04T14:40:23.735327Z | false |
psf/black | https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/remove_parens.py | tests/data/cases/remove_parens.py | x = (1)
x = (1.2)
data = (
"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
).encode()
async def show_status():
while True:
try:
if report_host:
data = (
f"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
).encode()
except Exception as e:
pass
def example():
return (("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"))
def example1():
return ((1111111111111111111111111111111111111111111111111111111111111111111111111111111111111))
def example1point5():
return ((((((1111111111111111111111111111111111111111111111111111111111111111111111111111111111111))))))
def example2():
return (("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"))
def example3():
return ((1111111111111111111111111111111111111111111111111111111111111111111111111111111))
def example4():
return ((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((True))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))
def example5():
return ((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((()))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))
def example6():
return ((((((((({a:a for a in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17]})))))))))
def example7():
return ((((((((({a:a for a in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20000000000000000000]})))))))))
def example8():
return (((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((None)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))
# output
x = 1
x = 1.2
data = (
"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
).encode()
async def show_status():
while True:
try:
if report_host:
data = (
f"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
).encode()
except Exception as e:
pass
def example():
return "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
def example1():
return 1111111111111111111111111111111111111111111111111111111111111111111111111111111111111
def example1point5():
return 1111111111111111111111111111111111111111111111111111111111111111111111111111111111111
def example2():
return (
"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
)
def example3():
return (
1111111111111111111111111111111111111111111111111111111111111111111111111111111
)
def example4():
return True
def example5():
return ()
def example6():
return {a: a for a in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17]}
def example7():
return {
a: a
for a in [
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20000000000000000000,
]
}
def example8():
return None
| python | MIT | c3cc5a95d4f72e6ccc27ebae23344fce8cc70786 | 2026-01-04T14:40:23.735327Z | false |
psf/black | https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/fmtskip6.py | tests/data/cases/fmtskip6.py | class A:
def f(self):
for line in range(10):
if True:
pass # fmt: skip
# output
class A:
def f(self):
for line in range(10):
if True:
pass # fmt: skip
| python | MIT | c3cc5a95d4f72e6ccc27ebae23344fce8cc70786 | 2026-01-04T14:40:23.735327Z | false |
psf/black | https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/fmtskip3.py | tests/data/cases/fmtskip3.py | a = 3
# fmt: off
b, c = 1, 2
d = 6 # fmt: skip
e = 5
# fmt: on
f = ["This is a very long line that should be formatted into a clearer line ", "by rearranging."]
# output
a = 3
# fmt: off
b, c = 1, 2
d = 6 # fmt: skip
e = 5
# fmt: on
f = [
"This is a very long line that should be formatted into a clearer line ",
"by rearranging.",
]
| python | MIT | c3cc5a95d4f72e6ccc27ebae23344fce8cc70786 | 2026-01-04T14:40:23.735327Z | false |
psf/black | https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/module_docstring_4.py | tests/data/cases/module_docstring_4.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/skip_magic_trailing_comma_generic_wrap.py | tests/data/cases/skip_magic_trailing_comma_generic_wrap.py | # flags: --minimum-version=3.12 --skip-magic-trailing-comma
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
# 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
| python | MIT | c3cc5a95d4f72e6ccc27ebae23344fce8cc70786 | 2026-01-04T14:40:23.735327Z | false |
psf/black | https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/composition.py | tests/data/cases/composition.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,
}
)
| python | MIT | c3cc5a95d4f72e6ccc27ebae23344fce8cc70786 | 2026-01-04T14:40:23.735327Z | false |
psf/black | https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/module_docstring_after_comment.py | tests/data/cases/module_docstring_after_comment.py | # flags: --preview
#!/python
# regression test for #4762
"""
docstring
"""
from __future__ import annotations
import os
# output
#!/python
# regression test for #4762
"""
docstring
"""
from __future__ import annotations
import os
| python | MIT | c3cc5a95d4f72e6ccc27ebae23344fce8cc70786 | 2026-01-04T14:40:23.735327Z | false |
psf/black | https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/preview_wrap_comprehension_in.py | tests/data/cases/preview_wrap_comprehension_in.py | # flags: --preview --line-length=79
[a for graph_path_expression in refined_constraint.condition_as_predicate.variables]
[
a
for graph_path_expression in refined_constraint.condition_as_predicate.variables
]
[
a
for graph_path_expression
in refined_constraint.condition_as_predicate.variables
]
[
a
for graph_path_expression in (
refined_constraint.condition_as_predicate.variables
)
]
[
(foobar_very_long_key, foobar_very_long_value)
for foobar_very_long_key, foobar_very_long_value in foobar_very_long_dictionary.items()
]
# Don't split the `in` if it's not too long
lcomp3 = [
element.split("\n", 1)[0]
for element in collection.select_elements()
# right
if element is not None
]
# Don't remove parens around ternaries
expected = [i for i in (a if b else c)]
# Nested arrays
# First in will not be split because it would still be too long
[[
x
for x in bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
for y in xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
]]
# Multiple comprehensions, only split the second `in`
graph_path_expressions_in_local_constraint_refinements = [
graph_path_expression
for refined_constraint in self._local_constraint_refinements.values()
if refined_constraint is not None
for graph_path_expression in refined_constraint.condition_as_predicate.variables
]
# Dictionary comprehensions
dict_with_really_long_names = {
really_really_long_key_name: an_even_longer_really_really_long_key_value
for really_really_long_key_name, an_even_longer_really_really_long_key_value in really_really_really_long_dict_name.items()
}
{
key_with_super_really_long_name: key_with_super_really_long_name
for key_with_super_really_long_name in dictionary_with_super_really_long_name
}
{
key_with_super_really_long_name: key_with_super_really_long_name
for key_with_super_really_long_name
in dictionary_with_super_really_long_name
}
{
key_with_super_really_long_name: key_with_super_really_long_name
for key in (
dictionary
)
}
# output
[
a
for graph_path_expression in (
refined_constraint.condition_as_predicate.variables
)
]
[
a
for graph_path_expression in (
refined_constraint.condition_as_predicate.variables
)
]
[
a
for graph_path_expression in (
refined_constraint.condition_as_predicate.variables
)
]
[
a
for graph_path_expression in (
refined_constraint.condition_as_predicate.variables
)
]
[
(foobar_very_long_key, foobar_very_long_value)
for foobar_very_long_key, foobar_very_long_value in (
foobar_very_long_dictionary.items()
)
]
# Don't split the `in` if it's not too long
lcomp3 = [
element.split("\n", 1)[0]
for element in collection.select_elements()
# right
if element is not None
]
# Don't remove parens around ternaries
expected = [i for i in (a if b else c)]
# Nested arrays
# First in will not be split because it would still be too long
[
[
x
for x in bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
for y in (
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
)
]
]
# Multiple comprehensions, only split the second `in`
graph_path_expressions_in_local_constraint_refinements = [
graph_path_expression
for refined_constraint in self._local_constraint_refinements.values()
if refined_constraint is not None
for graph_path_expression in (
refined_constraint.condition_as_predicate.variables
)
]
# Dictionary comprehensions
dict_with_really_long_names = {
really_really_long_key_name: an_even_longer_really_really_long_key_value
for really_really_long_key_name, an_even_longer_really_really_long_key_value in (
really_really_really_long_dict_name.items()
)
}
{
key_with_super_really_long_name: key_with_super_really_long_name
for key_with_super_really_long_name in (
dictionary_with_super_really_long_name
)
}
{
key_with_super_really_long_name: key_with_super_really_long_name
for key_with_super_really_long_name in (
dictionary_with_super_really_long_name
)
}
{
key_with_super_really_long_name: key_with_super_really_long_name
for key in dictionary
}
| python | MIT | c3cc5a95d4f72e6ccc27ebae23344fce8cc70786 | 2026-01-04T14:40:23.735327Z | false |
psf/black | https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/backslash_before_indent.py | tests/data/cases/backslash_before_indent.py | # flags: --minimum-version=3.10
class Plotter:
\
pass
class AnotherCase:
\
"""Some
\
Docstring
"""
# output
class Plotter:
pass
class AnotherCase:
"""Some
\
Docstring
"""
| python | MIT | c3cc5a95d4f72e6ccc27ebae23344fce8cc70786 | 2026-01-04T14:40:23.735327Z | false |
psf/black | https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/docstring_newline.py | tests/data/cases/docstring_newline.py | """
87 characters ............................................................................
"""
| python | MIT | c3cc5a95d4f72e6ccc27ebae23344fce8cc70786 | 2026-01-04T14:40:23.735327Z | false |
psf/black | https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/trailing_commas_in_leading_parts.py | tests/data/cases/trailing_commas_in_leading_parts.py | zero(one,).two(three,).four(five,)
func1(arg1).func2(arg2,).func3(arg3).func4(arg4,).func5(arg5)
# Inner one-element tuple shouldn't explode
func1(arg1).func2(arg1, (one_tuple,)).func3(arg3)
(a, b, c, d,) = func1(arg1) and func2(arg2)
# Example from https://github.com/psf/black/issues/3229
def refresh_token(self, device_family, refresh_token, api_key):
return self.orchestration.refresh_token(
data={
"refreshToken": refresh_token,
},
api_key=api_key,
)["extensions"]["sdk"]["token"]
# Edge case where a bug in a working-in-progress version of
# https://github.com/psf/black/pull/3370 causes an infinite recursion.
assert (
long_module.long_class.long_func().another_func()
== long_module.long_class.long_func()["some_key"].another_func(arg1)
)
# Regression test for https://github.com/psf/black/issues/3414.
assert xxxxxxxxx.xxxxxxxxx.xxxxxxxxx(
xxxxxxxxx
).xxxxxxxxxxxxxxxxxx(), (
"xxx {xxxxxxxxx} xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
)
# output
zero(
one,
).two(
three,
).four(
five,
)
func1(arg1).func2(
arg2,
).func3(arg3).func4(
arg4,
).func5(arg5)
# Inner one-element tuple shouldn't explode
func1(arg1).func2(arg1, (one_tuple,)).func3(arg3)
(
a,
b,
c,
d,
) = func1(
arg1
) and func2(arg2)
# Example from https://github.com/psf/black/issues/3229
def refresh_token(self, device_family, refresh_token, api_key):
return self.orchestration.refresh_token(
data={
"refreshToken": refresh_token,
},
api_key=api_key,
)["extensions"]["sdk"]["token"]
# Edge case where a bug in a working-in-progress version of
# https://github.com/psf/black/pull/3370 causes an infinite recursion.
assert (
long_module.long_class.long_func().another_func()
== long_module.long_class.long_func()["some_key"].another_func(arg1)
)
# Regression test for https://github.com/psf/black/issues/3414.
assert xxxxxxxxx.xxxxxxxxx.xxxxxxxxx(
xxxxxxxxx
).xxxxxxxxxxxxxxxxxx(), (
"xxx {xxxxxxxxx} xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
)
| python | MIT | c3cc5a95d4f72e6ccc27ebae23344fce8cc70786 | 2026-01-04T14:40:23.735327Z | false |
psf/black | https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/parenthesized_context_managers.py | tests/data/cases/parenthesized_context_managers.py | # flags: --minimum-version=3.10
with (CtxManager() as example):
...
with (CtxManager1(), CtxManager2()):
...
with (CtxManager1() as example, CtxManager2()):
...
with (CtxManager1(), CtxManager2() as example):
...
with (CtxManager1() as example1, CtxManager2() as example2):
...
with (
CtxManager1() as example1,
CtxManager2() as example2,
CtxManager3() as example3,
):
...
# output
with CtxManager() as example:
...
with CtxManager1(), CtxManager2():
...
with CtxManager1() as example, CtxManager2():
...
with CtxManager1(), CtxManager2() as example:
...
with CtxManager1() as example1, CtxManager2() as example2:
...
with (
CtxManager1() as example1,
CtxManager2() as example2,
CtxManager3() as example3,
):
...
| python | MIT | c3cc5a95d4f72e6ccc27ebae23344fce8cc70786 | 2026-01-04T14:40:23.735327Z | false |
psf/black | https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/fmtskip7.py | tests/data/cases/fmtskip7.py | a = "this is some code"
b = 5 # fmt:skip
c = 9 #fmt: skip
d = "thisisasuperlongstringthisisasuperlongstringthisisasuperlongstringthisisasuperlongstring" # fmt:skip
# output
a = "this is some code"
b = 5 # fmt:skip
c = 9 #fmt: skip
d = "thisisasuperlongstringthisisasuperlongstringthisisasuperlongstringthisisasuperlongstring" # fmt:skip
| python | MIT | c3cc5a95d4f72e6ccc27ebae23344fce8cc70786 | 2026-01-04T14:40:23.735327Z | false |
psf/black | https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/comments_in_blocks.py | tests/data/cases/comments_in_blocks.py | # Test cases from:
# - https://github.com/psf/black/issues/1798
# - https://github.com/psf/black/issues/1499
# - https://github.com/psf/black/issues/1211
# - https://github.com/psf/black/issues/563
(
lambda
# a comment
: None
)
(
lambda:
# b comment
None
)
(
lambda
# a comment
:
# b comment
None
)
[
x
# Let's do this
for
# OK?
x
# Some comment
# And another
in
# One more
y
]
return [
(offers[offer_index], 1.0)
for offer_index, _
# avoid returning any offers that don't match the grammar so
# that the return values here are consistent with what would be
# returned in AcceptValidHeader
in self._parse_and_normalize_offers(offers)
]
from foo import (
bar,
# qux
)
def convert(collection):
# replace all variables by integers
replacement_dict = {
variable: f"{index}"
for index, variable
# 0 is reserved as line terminator
in enumerate(collection.variables(), start=1)
}
{
i: i
for i
# a comment
in range(5)
}
def get_subtree_proof_nodes(
chunk_index_groups: Sequence[Tuple[int, ...], ...],
) -> Tuple[int, ...]:
subtree_node_paths = (
# We take a candidate element from each group and shift it to
# remove the bits that are not common to other group members, then
# we convert it to a tree path that all elements from this group
# have in common.
chunk_index
for chunk_index, bits_to_truncate
# Each group will contain an even "power-of-two" number of# elements.
# This tells us how many tailing bits each element has# which need to
# be truncated to get the group's common prefix.
in ((group[0], (len(group) - 1).bit_length()) for group in chunk_index_groups)
)
return subtree_node_paths
if (
# comment1
a
# comment2
or (
# comment3
(
# comment4
b
)
# comment5
and
# comment6
c
or (
# comment7
d
)
)
):
print("Foo")
| 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_class.py | tests/data/cases/module_docstring_followed_by_class.py | """Two blank lines between module docstring and a class."""
class MyClass:
pass
# output
"""Two blank lines between module docstring and a class."""
class MyClass:
pass
| python | MIT | c3cc5a95d4f72e6ccc27ebae23344fce8cc70786 | 2026-01-04T14:40:23.735327Z | false |
psf/black | https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/fmtonoff.py | tests/data/cases/fmtonoff.py | #!/usr/bin/env python3
import asyncio
import sys
from third_party import X, Y, Z
from library import some_connection, \
some_decorator
# fmt: off
from third_party import (X,
Y, Z)
# fmt: on
f'trigger 3.6 mode'
# Comment 1
# Comment 2
# fmt: off
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]
# fmt: on
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(1, 2)))
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)):
...
something = {
# fmt: off
key: 'value',
}
def subscriptlist():
atom[
# fmt: off
'some big and',
'complex subscript',
# fmt: on
goes + here, andhere,
]
def import_as_names():
# fmt: off
from hello import a, b
'unformatted'
# fmt: on
def testlist_star_expr():
# fmt: off
a , b = *hello
'unformatted'
# fmt: on
def yield_expr():
# fmt: off
yield hello
'unformatted'
# fmt: on
'formatted'
# fmt: off
( yield hello )
'unformatted'
# fmt: on
def example(session):
# fmt: off
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()
# fmt: on
def off_and_on_without_data():
"""Test that comment-only fmt:off/on blocks preserve formatting."""
# fmt: off
#should not be formatted
# fmt: on
# fmt: off
#should not be formatted
# fmt: on
# fmt: off
#should not be formatted
#should not be formatted #also should not be formatted
# fmt: on
pass
def on_and_off_with_comment_only_blocks():
"""Test that fmt:off/on works with multiple directives and comment-only blocks."""
# fmt: on
# fmt: off
this=should.not_be.formatted()
and_=indeed . it is not formatted
because . the . handling . inside . generate_ignored_nodes()
now . considers . multiple . fmt . directives . within . one . prefix
# fmt: on
# fmt: off
#should not be formatted
# fmt: on
# fmt: off
#should not be formatted
# fmt: on
# fmt: off
#should not be formatted
#should not be formatted #also should not be formatted
# fmt: on
def long_lines():
if True:
typedargslist.extend(
gen_annotated_params(ast_args.kwonlyargs, ast_args.kw_defaults, parameters, implicit_default=True)
)
# fmt: off
a = (
unnecessary_bracket()
)
# fmt: on
_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?
)
$
""",
# fmt: off
re.MULTILINE|re.VERBOSE
# fmt: on
)
def single_literal_yapf_disable():
"""Black does not support this."""
BAZ = {
(1, 2, 3, 4),
(5, 6, 7, 8),
(9, 10, 11, 12)
} # yapf: disable
cfg.rule(
"Default", "address",
xxxx_xxxx=["xxx-xxxxxx-xxxxxxxxxx"],
xxxxxx="xx_xxxxx", xxxxxxx="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
xxxxxxxxx_xxxx=True, xxxxxxxx_xxxxxxxxxx=False,
xxxxxx_xxxxxx=2, xxxxxx_xxxxx_xxxxxxxx=70, xxxxxx_xxxxxx_xxxxx=True,
# fmt: off
xxxxxxx_xxxxxxxxxxxx={
"xxxxxxxx": {
"xxxxxx": False,
"xxxxxxx": False,
"xxxx_xxxxxx": "xxxxx",
},
"xxxxxxxx-xxxxx": {
"xxxxxx": False,
"xxxxxxx": True,
"xxxx_xxxxxx": "xxxxxx",
},
},
# fmt: on
xxxxxxxxxx_xxxxxxxxxxx_xxxxxxx_xxxxxxxxx=5
)
# Test comment-only blocks at file level with various spacing patterns
# fmt: off
#nospace
# twospaces
# fmt: on
# fmt: off
#nospaceatall
#extraspaces
#evenmorespaces
# fmt: on
# fmt: off
# fmt: on
# fmt: off
#SBATCH --job-name=test
#SBATCH --output=test.out
# fmt: on
# fmt: off
#first
#second
# fmt: on
# fmt: off
#!@#$%^&*()
#<=>+-*/
# fmt: on
# fmt: off
#x=1+2
#y = 3
#z = 4
# fmt: on
# fmt: off
yield 'hello'
# No formatting to the end of the file
l=[1,2,3]
d={'a':1,
'b':2}
# output
#!/usr/bin/env python3
import asyncio
import sys
from third_party import X, Y, Z
from library import some_connection, some_decorator
# fmt: off
from third_party import (X,
Y, Z)
# fmt: on
f"trigger 3.6 mode"
# Comment 1
# Comment 2
# fmt: off
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]
# fmt: on
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(1, 2)))
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)): ...
something = {
# fmt: off
key: 'value',
}
def subscriptlist():
atom[
# fmt: off
'some big and',
'complex subscript',
# fmt: on
goes + here,
andhere,
]
def import_as_names():
# fmt: off
from hello import a, b
'unformatted'
# fmt: on
def testlist_star_expr():
# fmt: off
a , b = *hello
'unformatted'
# fmt: on
def yield_expr():
# fmt: off
yield hello
'unformatted'
# fmt: on
"formatted"
# fmt: off
( yield hello )
'unformatted'
# fmt: on
def example(session):
# fmt: off
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()
# fmt: on
def off_and_on_without_data():
"""Test that comment-only fmt:off/on blocks preserve formatting."""
# fmt: off
#should not be formatted
# fmt: on
# fmt: off
#should not be formatted
# fmt: on
# fmt: off
#should not be formatted
#should not be formatted #also should not be formatted
# fmt: on
pass
def on_and_off_with_comment_only_blocks():
"""Test that fmt:off/on works with multiple directives and comment-only blocks."""
# fmt: on
# fmt: off
this=should.not_be.formatted()
and_=indeed . it is not formatted
because . the . handling . inside . generate_ignored_nodes()
now . considers . multiple . fmt . directives . within . one . prefix
# fmt: off
#should not be formatted
# fmt: on
# fmt: off
#should not be formatted
# fmt: on
# fmt: off
#should not be formatted
#should not be formatted #also should not be formatted
# fmt: on
def long_lines():
if True:
typedargslist.extend(
gen_annotated_params(
ast_args.kwonlyargs,
ast_args.kw_defaults,
parameters,
implicit_default=True,
)
)
# fmt: off
a = (
unnecessary_bracket()
)
# fmt: on
_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?
)
$
""",
# fmt: off
re.MULTILINE|re.VERBOSE
# fmt: on
)
def single_literal_yapf_disable():
"""Black does not support this."""
BAZ = {(1, 2, 3, 4), (5, 6, 7, 8), (9, 10, 11, 12)} # yapf: disable
cfg.rule(
"Default",
"address",
xxxx_xxxx=["xxx-xxxxxx-xxxxxxxxxx"],
xxxxxx="xx_xxxxx",
xxxxxxx="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
xxxxxxxxx_xxxx=True,
xxxxxxxx_xxxxxxxxxx=False,
xxxxxx_xxxxxx=2,
xxxxxx_xxxxx_xxxxxxxx=70,
xxxxxx_xxxxxx_xxxxx=True,
# fmt: off
xxxxxxx_xxxxxxxxxxxx={
"xxxxxxxx": {
"xxxxxx": False,
"xxxxxxx": False,
"xxxx_xxxxxx": "xxxxx",
},
"xxxxxxxx-xxxxx": {
"xxxxxx": False,
"xxxxxxx": True,
"xxxx_xxxxxx": "xxxxxx",
},
},
# fmt: on
xxxxxxxxxx_xxxxxxxxxxx_xxxxxxx_xxxxxxxxx=5,
)
# Test comment-only blocks at file level with various spacing patterns
# fmt: off
#nospace
# twospaces
# fmt: on
# fmt: off
#nospaceatall
#extraspaces
#evenmorespaces
# fmt: on
# fmt: off
# fmt: on
# fmt: off
#SBATCH --job-name=test
#SBATCH --output=test.out
# fmt: on
# fmt: off
#first
#second
# fmt: on
# fmt: off
#!@#$%^&*()
#<=>+-*/
# fmt: on
# fmt: off
#x=1+2
#y = 3
#z = 4
# fmt: on
# fmt: off
yield 'hello'
# No formatting to the end of the file
l=[1,2,3]
d={'a':1,
'b':2}
| python | MIT | c3cc5a95d4f72e6ccc27ebae23344fce8cc70786 | 2026-01-04T14:40:23.735327Z | false |
psf/black | https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/miscellaneous/force_pyi.py | tests/data/miscellaneous/force_pyi.py | # flags: --pyi
from typing import Union
@bird
def zoo(): ...
class A: ...
@bar
class B:
def BMethod(self) -> None: ...
@overload
def BMethod(self, arg : List[str]) -> None: ...
class C: ...
@hmm
class D: ...
class E: ...
@baz
def foo() -> None:
...
class F (A , C): ...
def spam() -> None: ...
@overload
def spam(arg: str) -> str: ...
var : int = 1
def eggs() -> Union[str, int]: ...
# output
from typing import Union
@bird
def zoo(): ...
class A: ...
@bar
class B:
def BMethod(self) -> None: ...
@overload
def BMethod(self, arg: List[str]) -> None: ...
class C: ...
@hmm
class D: ...
class E: ...
@baz
def foo() -> None: ...
class F(A, C): ...
def spam() -> None: ...
@overload
def spam(arg: str) -> str: ...
var: int = 1
def eggs() -> Union[str, int]: ...
| python | MIT | c3cc5a95d4f72e6ccc27ebae23344fce8cc70786 | 2026-01-04T14:40:23.735327Z | false |
psf/black | https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/miscellaneous/pattern_matching_invalid.py | tests/data/miscellaneous/pattern_matching_invalid.py | # First match, no errors
match something:
case bla():
pass
# Problem on line 10
match invalid_case:
case valid_case:
pass
case a := b:
pass
case valid_case:
pass
# No problems either
match something:
case bla():
pass
| python | MIT | c3cc5a95d4f72e6ccc27ebae23344fce8cc70786 | 2026-01-04T14:40:23.735327Z | false |
psf/black | https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/miscellaneous/missing_final_newline.py | tests/data/miscellaneous/missing_final_newline.py | # A comment-only file, with no final EOL character
# This triggers https://bugs.python.org/issue2142
# This is the line without the EOL character | python | MIT | c3cc5a95d4f72e6ccc27ebae23344fce8cc70786 | 2026-01-04T14:40:23.735327Z | false |
psf/black | https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/miscellaneous/force_py36.py | tests/data/miscellaneous/force_py36.py | # The input source must not contain any Py36-specific syntax (e.g. argument type
# annotations, trailing comma after *rest) or this test becomes invalid.
def long_function_name(argument_one, argument_two, argument_three, argument_four, argument_five, argument_six, *rest): pass
# output
# The input source must not contain any Py36-specific syntax (e.g. argument type
# annotations, trailing comma after *rest) or this test becomes invalid.
def long_function_name(
argument_one,
argument_two,
argument_three,
argument_four,
argument_five,
argument_six,
*rest,
):
pass
| python | MIT | c3cc5a95d4f72e6ccc27ebae23344fce8cc70786 | 2026-01-04T14:40:23.735327Z | false |
psf/black | https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/miscellaneous/decorators.py | tests/data/miscellaneous/decorators.py | # This file doesn't use the standard decomposition.
# Decorator syntax test cases are separated by double # comments.
# Those before the 'output' comment are valid under the old syntax.
# Those after the 'ouput' comment require PEP614 relaxed syntax.
# Do not remove the double # separator before the first test case, it allows
# the comment before the test case to be ignored.
##
@decorator
def f():
...
##
@decorator()
def f():
...
##
@decorator(arg)
def f():
...
##
@decorator(kwarg=0)
def f():
...
##
@decorator(*args)
def f():
...
##
@decorator(**kwargs)
def f():
...
##
@decorator(*args, **kwargs)
def f():
...
##
@decorator(*args, **kwargs,)
def f():
...
##
@dotted.decorator
def f():
...
##
@dotted.decorator(arg)
def f():
...
##
@dotted.decorator(kwarg=0)
def f():
...
##
@dotted.decorator(*args)
def f():
...
##
@dotted.decorator(**kwargs)
def f():
...
##
@dotted.decorator(*args, **kwargs)
def f():
...
##
@dotted.decorator(*args, **kwargs,)
def f():
...
##
@double.dotted.decorator
def f():
...
##
@double.dotted.decorator(arg)
def f():
...
##
@double.dotted.decorator(kwarg=0)
def f():
...
##
@double.dotted.decorator(*args)
def f():
...
##
@double.dotted.decorator(**kwargs)
def f():
...
##
@double.dotted.decorator(*args, **kwargs)
def f():
...
##
@double.dotted.decorator(*args, **kwargs,)
def f():
...
##
@_(sequence["decorator"])
def f():
...
##
@eval("sequence['decorator']")
def f():
...
# output
##
@decorator()()
def f():
...
##
@(decorator)
def f():
...
##
@sequence["decorator"]
def f():
...
##
@decorator[List[str]]
def f():
...
##
@var := decorator
def f():
... | python | MIT | c3cc5a95d4f72e6ccc27ebae23344fce8cc70786 | 2026-01-04T14:40:23.735327Z | false |
psf/black | https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/miscellaneous/async_as_identifier.py | tests/data/miscellaneous/async_as_identifier.py | def async():
pass
def await():
pass
await = lambda: None
async = lambda: None
async()
await()
def sync_fn():
await = lambda: None
async = lambda: None
async()
await()
async def async_fn():
await async_fn()
# output
def async():
pass
def await():
pass
await = lambda: None
async = lambda: None
async()
await()
def sync_fn():
await = lambda: None
async = lambda: None
async()
await()
async def async_fn():
await async_fn()
| python | MIT | c3cc5a95d4f72e6ccc27ebae23344fce8cc70786 | 2026-01-04T14:40:23.735327Z | false |
psf/black | https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/miscellaneous/blackd_diff.py | tests/data/miscellaneous/blackd_diff.py | def abc ():
return ["hello", "world",
"!"]
print( "Incorrect formatting"
)
| python | MIT | c3cc5a95d4f72e6ccc27ebae23344fce8cc70786 | 2026-01-04T14:40:23.735327Z | false |
psf/black | https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/miscellaneous/string_quotes.py | tests/data/miscellaneous/string_quotes.py | ''''''
'\''
'"'
"'"
"\""
"Hello"
"Don't do that"
'Here is a "'
'What\'s the deal here?'
"What's the deal \"here\"?"
"And \"here\"?"
"""Strings with "" in them"""
'''Strings with "" in them'''
'''Here's a "'''
'''Here's a " '''
'''Just a normal triple
quote'''
f"just a normal {f} string"
f'''This is a triple-quoted {f}-string'''
f'MOAR {" ".join([])}'
f"MOAR {' '.join([])}"
r"raw string ftw"
r'Date d\'expiration:(.*)'
r'Tricky "quote'
r'Not-so-tricky \"quote'
rf'{yay}'
'\n\
The \"quick\"\n\
brown fox\n\
jumps over\n\
the \'lazy\' dog.\n\
'
re.compile(r'[\\"]')
"x = ''; y = \"\""
"x = '''; y = \"\""
"x = ''''; y = \"\""
"x = '' ''; y = \"\""
"x = ''; y = \"\"\""
"x = '''; y = \"\"\"\""
"x = ''''; y = \"\"\"\"\""
"x = '' ''; y = \"\"\"\"\""
'unnecessary \"\"escaping'
"unnecessary \'\'escaping"
'\\""'
"\\''"
'Lots of \\\\\\\\\'quotes\''
f'{y * " "} \'{z}\''
f'{{y * " "}} \'{z}\''
f'\'{z}\' {y * " "}'
f'{y * x} \'{z}\''
'\'{z}\' {y * " "}'
'{y * x} \'{z}\''
# We must bail out if changing the quotes would introduce backslashes in f-string
# expressions. xref: https://github.com/psf/black/issues/2348
f"\"{b}\"{' ' * (long-len(b)+1)}: \"{sts}\",\n"
f"\"{a}\"{'hello' * b}\"{c}\""
# output
""""""
"'"
'"'
"'"
'"'
"Hello"
"Don't do that"
'Here is a "'
"What's the deal here?"
'What\'s the deal "here"?'
'And "here"?'
"""Strings with "" in them"""
"""Strings with "" in them"""
'''Here's a "'''
"""Here's a " """
"""Just a normal triple
quote"""
f"just a normal {f} string"
f"""This is a triple-quoted {f}-string"""
f'MOAR {" ".join([])}'
f"MOAR {' '.join([])}"
r"raw string ftw"
r"Date d\'expiration:(.*)"
r'Tricky "quote'
r"Not-so-tricky \"quote"
rf"{yay}"
"\nThe \"quick\"\nbrown fox\njumps over\nthe 'lazy' dog.\n"
re.compile(r'[\\"]')
"x = ''; y = \"\""
"x = '''; y = \"\""
"x = ''''; y = \"\""
"x = '' ''; y = \"\""
'x = \'\'; y = """'
'x = \'\'\'; y = """"'
'x = \'\'\'\'; y = """""'
'x = \'\' \'\'; y = """""'
'unnecessary ""escaping'
"unnecessary ''escaping"
'\\""'
"\\''"
"Lots of \\\\\\\\'quotes'"
f'{y * " "} \'{z}\''
f"{{y * \" \"}} '{z}'"
f'\'{z}\' {y * " "}'
f"{y * x} '{z}'"
"'{z}' {y * \" \"}"
"{y * x} '{z}'"
# We must bail out if changing the quotes would introduce backslashes in f-string
# expressions. xref: https://github.com/psf/black/issues/2348
f"\"{b}\"{' ' * (long-len(b)+1)}: \"{sts}\",\n"
f"\"{a}\"{'hello' * b}\"{c}\""
| python | MIT | c3cc5a95d4f72e6ccc27ebae23344fce8cc70786 | 2026-01-04T14:40:23.735327Z | false |
psf/black | https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/miscellaneous/debug_visitor.py | tests/data/miscellaneous/debug_visitor.py | @dataclass
class DebugVisitor(Visitor[T]):
tree_depth: int = 0
def visit_default(self, node: LN) -> Iterator[T]:
indent = ' ' * (2 * self.tree_depth)
if isinstance(node, Node):
_type = type_repr(node.type)
out(f'{indent}{_type}', fg='yellow')
self.tree_depth += 1
for child in node.children:
yield from self.visit(child)
self.tree_depth -= 1
out(f'{indent}/{_type}', fg='yellow', bold=False)
else:
_type = token.tok_name.get(node.type, str(node.type))
out(f'{indent}{_type}', fg='blue', nl=False)
if node.prefix:
# We don't have to handle prefixes for `Node` objects since
# that delegates to the first child anyway.
out(f' {node.prefix!r}', fg='green', bold=False, nl=False)
out(f' {node.value!r}', fg='blue', bold=False)
@classmethod
def show(cls, code: str) -> None:
"""Pretty-prints a given string of `code`.
Convenience method for debugging.
"""
v: DebugVisitor[None] = DebugVisitor()
list(v.visit(lib2to3_parse(code)))
| python | MIT | c3cc5a95d4f72e6ccc27ebae23344fce8cc70786 | 2026-01-04T14:40:23.735327Z | false |
psf/black | https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/miscellaneous/invalid_header.py | tests/data/miscellaneous/invalid_header.py | This is not valid Python syntax
y = "This is valid syntax"
| python | MIT | c3cc5a95d4f72e6ccc27ebae23344fce8cc70786 | 2026-01-04T14:40:23.735327Z | false |
psf/black | https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/miscellaneous/python2_detection.py | tests/data/miscellaneous/python2_detection.py | # This uses a similar construction to the decorators.py test data file FYI.
print "hello, world!"
###
exec "print('hello, world!')"
###
def set_position((x, y), value):
pass
###
try:
pass
except Exception, err:
pass
###
raise RuntimeError, "I feel like crashing today :p"
###
`wow_these_really_did_exist`
###
10L
###
10l
###
0123
# output
print("hello python three!")
###
exec("I'm not sure if you can use exec like this but that's not important here!")
###
try:
pass
except make_exception(1, 2):
pass
###
try:
pass
except Exception as err:
pass
###
raise RuntimeError(make_msg(1, 2))
###
raise RuntimeError("boom!",)
###
def set_position(x, y, value):
pass
###
10
###
0
###
000
###
0o12 | python | MIT | c3cc5a95d4f72e6ccc27ebae23344fce8cc70786 | 2026-01-04T14:40:23.735327Z | false |
psf/black | https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/invalid_nested_gitignore_tests/a.py | tests/data/invalid_nested_gitignore_tests/a.py | python | MIT | c3cc5a95d4f72e6ccc27ebae23344fce8cc70786 | 2026-01-04T14:40:23.735327Z | false | |
psf/black | https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/invalid_nested_gitignore_tests/a/a.py | tests/data/invalid_nested_gitignore_tests/a/a.py | python | MIT | c3cc5a95d4f72e6ccc27ebae23344fce8cc70786 | 2026-01-04T14:40:23.735327Z | false | |
psf/black | https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/ignore_directory_gitignore_tests/z.py | tests/data/ignore_directory_gitignore_tests/z.py | python | MIT | c3cc5a95d4f72e6ccc27ebae23344fce8cc70786 | 2026-01-04T14:40:23.735327Z | false | |
psf/black | https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/ignore_directory_gitignore_tests/abc.py | tests/data/ignore_directory_gitignore_tests/abc.py | python | MIT | c3cc5a95d4f72e6ccc27ebae23344fce8cc70786 | 2026-01-04T14:40:23.735327Z | false | |
psf/black | https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/ignore_directory_gitignore_tests/large_ignored_dir_two/a.py | tests/data/ignore_directory_gitignore_tests/large_ignored_dir_two/a.py | python | MIT | c3cc5a95d4f72e6ccc27ebae23344fce8cc70786 | 2026-01-04T14:40:23.735327Z | false | |
psf/black | https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/ignore_directory_gitignore_tests/large_ignored_dir_two/inner3/d.py | tests/data/ignore_directory_gitignore_tests/large_ignored_dir_two/inner3/d.py | python | MIT | c3cc5a95d4f72e6ccc27ebae23344fce8cc70786 | 2026-01-04T14:40:23.735327Z | false | |
psf/black | https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/ignore_directory_gitignore_tests/large_ignored_dir_two/inner/b.py | tests/data/ignore_directory_gitignore_tests/large_ignored_dir_two/inner/b.py | python | MIT | c3cc5a95d4f72e6ccc27ebae23344fce8cc70786 | 2026-01-04T14:40:23.735327Z | false | |
psf/black | https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/ignore_directory_gitignore_tests/large_ignored_dir_two/inner2/c.py | tests/data/ignore_directory_gitignore_tests/large_ignored_dir_two/inner2/c.py | python | MIT | c3cc5a95d4f72e6ccc27ebae23344fce8cc70786 | 2026-01-04T14:40:23.735327Z | false | |
psf/black | https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/invalid_gitignore_tests/a.py | tests/data/invalid_gitignore_tests/a.py | python | MIT | c3cc5a95d4f72e6ccc27ebae23344fce8cc70786 | 2026-01-04T14:40:23.735327Z | false | |
psf/black | https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/line_ranges_formatted/basic.py | tests/data/line_ranges_formatted/basic.py | """Module doc."""
from typing import (
Callable,
Literal,
)
# fmt: off
class Unformatted:
def should_also_work(self):
pass
# fmt: on
a = [1, 2] # fmt: skip
# This should cover as many syntaxes as possible.
class Foo:
"""Class doc."""
def __init__(self) -> None:
pass
@add_logging
@memoize.memoize(max_items=2)
def plus_one(
self,
number: int,
) -> int:
return number + 1
async def async_plus_one(self, number: int) -> int:
await asyncio.sleep(1)
async with some_context():
return number + 1
try:
for i in range(10):
while condition:
if something:
then_something()
elif something_else:
then_something_else()
except ValueError as e:
handle(e)
finally:
done()
| python | MIT | c3cc5a95d4f72e6ccc27ebae23344fce8cc70786 | 2026-01-04T14:40:23.735327Z | false |
psf/black | https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/line_ranges_formatted/pattern_matching.py | tests/data/line_ranges_formatted/pattern_matching.py | # flags: --minimum-version=3.10
def pattern_matching():
match status:
case 1:
return "1"
case [single]:
return "single"
case [
action,
obj,
]:
return "act on obj"
case Point(x=0):
return "class pattern"
case {"text": message}:
return "mapping"
case {
"text": message,
"format": _,
}:
return "mapping"
case _:
return "fallback"
| python | MIT | c3cc5a95d4f72e6ccc27ebae23344fce8cc70786 | 2026-01-04T14:40:23.735327Z | false |
psf/black | https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/include_exclude_tests/b/dont_exclude/a.py | tests/data/include_exclude_tests/b/dont_exclude/a.py | python | MIT | c3cc5a95d4f72e6ccc27ebae23344fce8cc70786 | 2026-01-04T14:40:23.735327Z | false | |
psf/black | https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/include_exclude_tests/b/.definitely_exclude/a.py | tests/data/include_exclude_tests/b/.definitely_exclude/a.py | python | MIT | c3cc5a95d4f72e6ccc27ebae23344fce8cc70786 | 2026-01-04T14:40:23.735327Z | false | |
psf/black | https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/include_exclude_tests/b/exclude/a.py | tests/data/include_exclude_tests/b/exclude/a.py | python | MIT | c3cc5a95d4f72e6ccc27ebae23344fce8cc70786 | 2026-01-04T14:40:23.735327Z | false | |
psf/black | https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/nested_gitignore_tests/x.py | tests/data/nested_gitignore_tests/x.py | python | MIT | c3cc5a95d4f72e6ccc27ebae23344fce8cc70786 | 2026-01-04T14:40:23.735327Z | false | |
psf/black | https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/nested_gitignore_tests/root/b.py | tests/data/nested_gitignore_tests/root/b.py | # should be included
| python | MIT | c3cc5a95d4f72e6ccc27ebae23344fce8cc70786 | 2026-01-04T14:40:23.735327Z | false |
psf/black | https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/nested_gitignore_tests/root/a.py | tests/data/nested_gitignore_tests/root/a.py | # should be excluded (root/.gitignore)
| python | MIT | c3cc5a95d4f72e6ccc27ebae23344fce8cc70786 | 2026-01-04T14:40:23.735327Z | false |
psf/black | https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/nested_gitignore_tests/root/c.py | tests/data/nested_gitignore_tests/root/c.py | # should be included
| python | MIT | c3cc5a95d4f72e6ccc27ebae23344fce8cc70786 | 2026-01-04T14:40:23.735327Z | false |
psf/black | https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/nested_gitignore_tests/root/child/b.py | tests/data/nested_gitignore_tests/root/child/b.py | # should be excluded (child/.gitignore)
| python | MIT | c3cc5a95d4f72e6ccc27ebae23344fce8cc70786 | 2026-01-04T14:40:23.735327Z | false |
psf/black | https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/nested_gitignore_tests/root/child/a.py | tests/data/nested_gitignore_tests/root/child/a.py | # should be excluded (root/.gitignore)
| python | MIT | c3cc5a95d4f72e6ccc27ebae23344fce8cc70786 | 2026-01-04T14:40:23.735327Z | false |
psf/black | https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/nested_gitignore_tests/root/child/c.py | tests/data/nested_gitignore_tests/root/child/c.py | # should be included
| python | MIT | c3cc5a95d4f72e6ccc27ebae23344fce8cc70786 | 2026-01-04T14:40:23.735327Z | false |
psf/black | https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/ignore_subfolders_gitignore_tests/a.py | tests/data/ignore_subfolders_gitignore_tests/a.py | python | MIT | c3cc5a95d4f72e6ccc27ebae23344fce8cc70786 | 2026-01-04T14:40:23.735327Z | false | |
psf/black | https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/ignore_subfolders_gitignore_tests/subdir/b.py | tests/data/ignore_subfolders_gitignore_tests/subdir/b.py | python | MIT | c3cc5a95d4f72e6ccc27ebae23344fce8cc70786 | 2026-01-04T14:40:23.735327Z | false | |
psf/black | https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/ignore_subfolders_gitignore_tests/subdir/subdir/c.py | tests/data/ignore_subfolders_gitignore_tests/subdir/subdir/c.py | python | MIT | c3cc5a95d4f72e6ccc27ebae23344fce8cc70786 | 2026-01-04T14:40:23.735327Z | false | |
psf/black | https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/gitignore_used_on_multiple_sources/dir2/b.py | tests/data/gitignore_used_on_multiple_sources/dir2/b.py | python | MIT | c3cc5a95d4f72e6ccc27ebae23344fce8cc70786 | 2026-01-04T14:40:23.735327Z | false | |
psf/black | https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/gitignore_used_on_multiple_sources/dir2/a.py | tests/data/gitignore_used_on_multiple_sources/dir2/a.py | python | MIT | c3cc5a95d4f72e6ccc27ebae23344fce8cc70786 | 2026-01-04T14:40:23.735327Z | false | |
psf/black | https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/gitignore_used_on_multiple_sources/dir1/b.py | tests/data/gitignore_used_on_multiple_sources/dir1/b.py | python | MIT | c3cc5a95d4f72e6ccc27ebae23344fce8cc70786 | 2026-01-04T14:40:23.735327Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.