Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[doc] Apply black on the documentation where it makes sense #8650

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,27 @@ repos:
- id: black
args: [--safe, --quiet]
exclude: *fixtures
- id: black
name: black-doc
Pierre-Sassoulas marked this conversation as resolved.
Show resolved Hide resolved
args: [--safe, --quiet]
files: doc/data/messages/
exclude: |
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can't we re-use this like we do with &fixtures and pass it in the pre-commit config?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What need to be in sync is the -l 103, black only looks at pyproject.toml so we have to give the option like this. (Alternatively we could use the default value, it's not super important.).

I don't think the exclude can be reused, this is the list of the message that black can fix automatically, it's really specific to black.

It's also a very useful list btw ! I'm considering to recover it automatically and generalize it to autofixxer (isort, autoflake, and ruff), in order to use this information directly in our doc for #8579

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I.e. if applying a tool on doc/data makes the tests fail on a m/my-message/bad.py file, then the tool autofix my-message. We might have to use it on functional tests instead for complicated fixes like ruff or autoflake to check which use cases is autofixed or not, but for black on the doc is enough and you get the idea.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, let's use the default then. Less config == better imo

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm going to need to rebase and rewrite black from zero, it's not THAT good with comment after all 😄

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shall we merge this and do another PR that removes the config?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No, it breaks the comments to go back to 88 char per line after doing 103 char per line, it's a lot easier to do it from scratch again :)

(?x)^(
doc/data/messages/b/bad-indentation/bad.py|
doc/data/messages/i/inconsistent-quotes/bad.py|
doc/data/messages/i/invalid-format-index/bad.py|
doc/data/messages/l/line-too-long/bad.py|
doc/data/messages/m/missing-final-newline/bad.py|
doc/data/messages/m/multiple-statements/bad.py|
doc/data/messages/r/redundant-u-string-prefix/bad.py|
doc/data/messages/s/superfluous-parens/bad.py|
doc/data/messages/s/syntax-error/bad.py|
doc/data/messages/t/too-many-ancestors/bad.py|
doc/data/messages/t/trailing-comma-tuple/bad.py|
doc/data/messages/t/trailing-newlines/bad.py|
doc/data/messages/t/trailing-whitespace/bad.py|
doc/data/messages/u/unnecessary-semicolon/bad.py
)$
- repo: https://github.com/Pierre-Sassoulas/black-disable-checker
rev: v1.1.3
hooks:
Expand Down
3 changes: 3 additions & 0 deletions doc/data/messages/a/arguments-renamed/bad.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,15 @@ class Fruit:
def brew(self, ingredient_name: str):
print(f"Brewing a {type(self)} with {ingredient_name}")


class Apple(Fruit):
...


class Orange(Fruit):
def brew(self, flavor: str): # [arguments-renamed]
print(f"Brewing an orange with {flavor}")


for fruit, ingredient_name in [[Orange(), "thyme"], [Apple(), "cinnamon"]]:
fruit.brew(ingredient_name=ingredient_name)
3 changes: 3 additions & 0 deletions doc/data/messages/a/arguments-renamed/good.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,15 @@ class Fruit:
def brew(self, ingredient_name: str):
print(f"Brewing a {type(self)} with {ingredient_name}")


class Apple(Fruit):
...


class Orange(Fruit):
def brew(self, ingredient_name: str):
print(f"Brewing an orange with {ingredient_name}")


for fruit, ingredient_name in [[Orange(), "thyme"], [Apple(), "cinnamon"]]:
fruit.brew(ingredient_name=ingredient_name)
2 changes: 1 addition & 1 deletion doc/data/messages/a/assigning-non-slot/bad.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
class Student:
__slots__ = ('name',)
__slots__ = ("name",)

def __init__(self, name, surname):
self.name = name
Expand Down
2 changes: 1 addition & 1 deletion doc/data/messages/a/assigning-non-slot/good.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
class Student:
__slots__ = ('name', 'surname')
__slots__ = ("name", "surname")

def __init__(self, name, surname):
self.name = name
Expand Down
4 changes: 3 additions & 1 deletion doc/data/messages/b/bad-chained-comparison/bad.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
def xor_check(*, left=None, right=None):
if left is None != right is None: # [bad-chained-comparison]
raise ValueError('Either both left= and right= need to be provided or none should.')
raise ValueError(
"Either both left= and right= need to be provided or none should."
)
4 changes: 3 additions & 1 deletion doc/data/messages/b/bad-chained-comparison/good.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
def xor_check(*, left=None, right=None):
if (left is None) != (right is None):
raise ValueError('Either both left= and right= need to be provided or none should.')
raise ValueError(
"Either both left= and right= need to be provided or none should."
)
1 change: 0 additions & 1 deletion doc/data/messages/b/bad-classmethod-argument/bad.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
class Klass:

@classmethod
def get_instance(self): # [bad-classmethod-argument]
return self()
1 change: 0 additions & 1 deletion doc/data/messages/b/bad-classmethod-argument/good.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
class Klass:

@classmethod
def get_instance(cls):
return cls()
2 changes: 1 addition & 1 deletion doc/data/messages/b/bad-docstring-quotes/bad.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
def foo(): # [bad-docstring-quotes]
'Docstring.'
"Docstring."
return
2 changes: 1 addition & 1 deletion doc/data/messages/b/bad-format-string/bad.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
print('{a[0] + a[1]}'.format(a=[0, 1])) # [bad-format-string]
print("{a[0] + a[1]}".format(a=[0, 1])) # [bad-format-string]
2 changes: 1 addition & 1 deletion doc/data/messages/b/bad-format-string/good.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
print('{a[0]} + {a[1]}'.format(a=[0, 1]))
print("{a[0]} + {a[1]}".format(a=[0, 1]))
2 changes: 1 addition & 1 deletion doc/data/messages/b/bad-indentation/good.py
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
if input():
print('yes')
print("yes")
2 changes: 1 addition & 1 deletion doc/data/messages/b/bad-thread-instantiation/bad.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@


def thread_target(n):
print(n ** 2)
print(n**2)


thread = threading.Thread(lambda: None) # [bad-thread-instantiation]
Expand Down
2 changes: 1 addition & 1 deletion doc/data/messages/b/bad-thread-instantiation/good.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@


def thread_target(n):
print(n ** 2)
print(n**2)


thread = threading.Thread(target=thread_target, args=(10,))
Expand Down
2 changes: 2 additions & 0 deletions doc/data/messages/c/cell-var-from-loop/bad.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
def foo(numbers):
for i in numbers:

def bar():
print(i) # [cell-var-from-loop]

bar()
2 changes: 1 addition & 1 deletion doc/data/messages/c/class-variable-slots-conflict/good.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
class Person:
__slots__ = ("_age", "name",)
__slots__ = ("_age", "name")

def __init__(self, age, name):
self._age = age
Expand Down
4 changes: 2 additions & 2 deletions doc/data/messages/c/compare-to-zero/bad.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
x = 0
y = 1

if x == 0: # [compare-to-zero]
if x == 0: # [compare-to-zero]
print("x is equal to zero")

if y != 0: # [compare-to-zero]
if y != 0: # [compare-to-zero]
print("y is not equal to zero")
1 change: 1 addition & 0 deletions doc/data/messages/c/comparison-with-callable/bad.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
def function_returning_a_fruit() -> str:
return "orange"


def is_an_orange(fruit: str = "apple"):
# apple == <function function_returning_a_fruit at 0x7f343ff0a1f0>
return fruit == function_returning_a_fruit # [comparison-with-callable]
1 change: 1 addition & 0 deletions doc/data/messages/c/comparison-with-callable/good.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
def function_returning_a_fruit() -> str:
return "orange"


def is_an_orange(fruit: str = "apple"):
# apple == orange
return fruit == function_returning_a_fruit()
2 changes: 1 addition & 1 deletion doc/data/messages/c/confusing-with-statement/bad.py
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
with open('file.txt', 'w') as fh1, fh2: # [confusing-with-statement]
with open("file.txt", "w") as fh1, fh2: # [confusing-with-statement]
pass
4 changes: 2 additions & 2 deletions doc/data/messages/c/confusing-with-statement/good.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
with open('file.txt', 'w', encoding="utf8") as fh1:
with open('file.txt', 'w', encoding="utf8") as fh2:
with open("file.txt", "w", encoding="utf8") as fh1:
with open("file.txt", "w", encoding="utf8") as fh2:
pass
3 changes: 2 additions & 1 deletion doc/data/messages/c/consider-merging-isinstance/bad.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,5 @@


def is_number(value: Any) -> bool:
return isinstance(value, int) or isinstance(value, float) # [consider-merging-isinstance]
# +1: [consider-merging-isinstance]
return isinstance(value, int) or isinstance(value, float)
2 changes: 1 addition & 1 deletion doc/data/messages/c/consider-using-any-or-all/good.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@

def any_even(items):
"""Return True if the list contains any even numbers"""
return any(item % 2 == 0 for item in items)


def all_even(items):
"""Return True if the list contains all even numbers"""
return all(item % 2 == 0 for item in items)
2 changes: 1 addition & 1 deletion doc/data/messages/c/consider-using-enumerate/bad.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
seasons = ['Spring', 'Summer', 'Fall', 'Winter']
seasons = ["Spring", "Summer", "Fall", "Winter"]

for i in range(len(seasons)): # [consider-using-enumerate]
print(i, seasons[i])
2 changes: 1 addition & 1 deletion doc/data/messages/c/consider-using-enumerate/good.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
seasons = ['Spring', 'Summer', 'Fall', 'Winter']
seasons = ["Spring", "Summer", "Fall", "Winter"]

for i, season in enumerate(seasons):
print(i, season)
2 changes: 1 addition & 1 deletion doc/data/messages/c/consider-using-f-string/good.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
menu = ('eggs', 'spam', 42.4)
menu = ("eggs", "spam", 42.4)

f_string_order = f"{menu[0]} and {menu[1]}: {menu[2]:0.2f} ¤"
3 changes: 2 additions & 1 deletion doc/data/messages/c/consider-using-in/bad.py
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
def fruit_is_round(fruit):
return fruit == "apple" or fruit == "orange" or fruit == "melon" # [consider-using-in]
# +1: [consider-using-in]
return fruit == "apple" or fruit == "orange" or fruit == "melon"
1 change: 1 addition & 0 deletions doc/data/messages/c/consider-using-join/bad.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,5 @@ def fruits_to_string(fruits):
formatted_fruit += fruit # [consider-using-join]
return formatted_fruit


print(fruits_to_string(["apple", "pear", "peach"]))
2 changes: 1 addition & 1 deletion doc/data/messages/d/deprecated-method/bad.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
import logging

logging.warn("I'm coming, world !") # [deprecated-method]
logging.warn("I'm coming, world !") # [deprecated-method]
4 changes: 2 additions & 2 deletions doc/data/messages/d/dict-init-mutate/bad.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
fruit_prices = {} # [dict-init-mutate]
fruit_prices['apple'] = 1
fruit_prices['banana'] = 10
fruit_prices["apple"] = 1
fruit_prices["banana"] = 10
2 changes: 1 addition & 1 deletion doc/data/messages/d/dict-iter-missing-items/bad.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
data = {'Paris': 2_165_423, 'New York City': 8_804_190, 'Tokyo': 13_988_129}
data = {"Paris": 2_165_423, "New York City": 8_804_190, "Tokyo": 13_988_129}
for city, population in data: # [dict-iter-missing-items]
print(f"{city} has population {population}.")
2 changes: 1 addition & 1 deletion doc/data/messages/d/dict-iter-missing-items/good.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
data = {'Paris': 2_165_423, 'New York City': 8_804_190, 'Tokyo': 13_988_129}
data = {"Paris": 2_165_423, "New York City": 8_804_190, "Tokyo": 13_988_129}
for city, population in data.items():
print(f"{city} has population {population}.")
2 changes: 1 addition & 1 deletion doc/data/messages/d/duplicate-code/bad/orange.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
class Orange: # [duplicate-code]
class Orange: # [duplicate-code]
def __init__(self):
self.remaining_bites = 3

Expand Down
2 changes: 1 addition & 1 deletion doc/data/messages/d/duplicate-value/bad.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
incorrect_set = {'value1', 23, 5, 'value1'} # [duplicate-value]
incorrect_set = {"value1", 23, 5, "value1"} # [duplicate-value]
2 changes: 1 addition & 1 deletion doc/data/messages/d/duplicate-value/good.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
correct_set = {'value1', 23, 5}
correct_set = {"value1", 23, 5}
9 changes: 5 additions & 4 deletions doc/data/messages/e/exec-used/good.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
def get_user_code(name):
return input(f'Enter code to be executed please, {name}: ')
return input(f"Enter code to be executed please, {name}: ")


username = "Ada"
allowed_globals = {'__builtins__' : None}
allowed_locals = {'print': print}
exec(get_user_code(username), allowed_globals, allowed_locals) # pylint: disable=exec-used
allowed_globals = {"__builtins__": None}
allowed_locals = {"print": print}
# pylint: disable-next=exec-used
exec(get_user_code(username), allowed_globals, allowed_locals)
9 changes: 7 additions & 2 deletions doc/data/messages/f/forgotten-debug-statement/bad.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,15 @@

def find_the_treasure(clues):
for clue in clues:
pdb.set_trace() # [forgotten-debug-statement]
pdb.set_trace() # [forgotten-debug-statement]
if "treasure" in clue:
return True
return False

treasure_hunt = ["Dead Man's Chest", "X marks the spot", "The treasure is buried near the palm tree"]

treasure_hunt = [
"Dead Man's Chest",
"X marks the spot",
"The treasure is buried near the palm tree",
]
find_the_treasure(treasure_hunt)
7 changes: 6 additions & 1 deletion doc/data/messages/f/forgotten-debug-statement/good.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,10 @@ def find_the_treasure(clues):
return True
return False

treasure_hunt = ["Dead Man's Chest", "X marks the spot", "The treasure is buried near the palm tree"]

treasure_hunt = [
"Dead Man's Chest",
"X marks the spot",
"The treasure is buried near the palm tree",
]
find_the_treasure(treasure_hunt)
2 changes: 1 addition & 1 deletion doc/data/messages/f/format-combined-specification/bad.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
print('{} {1}'.format('hello', 'world')) # [format-combined-specification]
print("{} {1}".format("hello", "world")) # [format-combined-specification]
4 changes: 2 additions & 2 deletions doc/data/messages/f/format-combined-specification/good.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
print('{0} {1}'.format('hello', 'world'))
print("{0} {1}".format("hello", "world"))
# or
print('{} {}'.format('hello', 'world'))
print("{} {}".format("hello", "world"))
1 change: 1 addition & 0 deletions doc/data/messages/i/import-outside-toplevel/bad.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
def print_python_version():
import sys # [import-outside-toplevel]

print(sys.version_info)
3 changes: 2 additions & 1 deletion doc/data/messages/i/import-private-name/bad.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

attr_holder = _AttributeHolder()


def add_sub_parser(sub_parsers: _SubParsersAction):
sub_parsers.add_parser('my_subparser')
sub_parsers.add_parser("my_subparser")
# ...
2 changes: 1 addition & 1 deletion doc/data/messages/i/import-private-name/good.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,5 @@


def add_sub_parser(sub_parsers: _SubParsersAction):
sub_parsers.add_parser('my_subparser')
sub_parsers.add_parser("my_subparser")
# ...
1 change: 1 addition & 0 deletions doc/data/messages/i/init-is-generator/bad.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,5 @@ class Fruit:
def __init__(self, worms): # [init-is-generator]
yield from worms


apple = Fruit(["Fahad", "Anisha", "Tabatha"])
1 change: 1 addition & 0 deletions doc/data/messages/i/init-is-generator/good.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ def __init__(self, worms):
def worms(self):
yield from self.__worms


apple = Fruit(["Fahad", "Anisha", "Tabatha"])
for worm in apple.worms():
pass
2 changes: 1 addition & 1 deletion doc/data/messages/i/invalid-all-format/bad.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
__all__ = ("CONST") # [invalid-all-format]
__all__ = "CONST" # [invalid-all-format]
Pierre-Sassoulas marked this conversation as resolved.
Show resolved Hide resolved

CONST = 42
2 changes: 2 additions & 0 deletions doc/data/messages/i/invalid-all-object/bad.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,10 @@
Worm,
)


class Fruit:
pass


class Worm:
pass
4 changes: 3 additions & 1 deletion doc/data/messages/i/invalid-all-object/good.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
__all__ = ['Fruit', 'Worm']
__all__ = ["Fruit", "Worm"]


class Fruit:
pass


class Worm:
pass
2 changes: 1 addition & 1 deletion doc/data/messages/i/invalid-character-backspace/bad.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
STRING = "Invalid character backspace " # [invalid-character-backspace]
STRING = "Invalid character backspace " # [invalid-character-backspace]
2 changes: 1 addition & 1 deletion doc/data/messages/i/invalid-character-esc/bad.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
STRING = "Invalid escape character " # [invalid-character-esc]
STRING = "Invalid escape character " # [invalid-character-esc]
2 changes: 1 addition & 1 deletion doc/data/messages/i/invalid-character-sub/bad.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
STRING = "Invalid character sub " # [invalid-character-sub]
STRING = "Invalid character sub " # [invalid-character-sub]
Original file line number Diff line number Diff line change
@@ -1 +1 @@
STRING = "Invalid character zero-width-space ​" # [invalid-character-zero-width-space]
STRING = "Invalid character zero-width-space ​" # [invalid-character-zero-width-space]
2 changes: 1 addition & 1 deletion doc/data/messages/i/invalid-envvar-default/bad.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
import os

env = os.getenv('SECRET_KEY', 1) # [invalid-envvar-default]
env = os.getenv("SECRET_KEY", 1) # [invalid-envvar-default]
2 changes: 1 addition & 1 deletion doc/data/messages/i/invalid-envvar-default/good.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
import os

env = os.getenv('SECRET_KEY', '1')
env = os.getenv("SECRET_KEY", "1")
Loading