Skip to content

FIX: Add pre-commit Blacken-docs hooks #54137

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

Closed
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
13 changes: 11 additions & 2 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ repos:
hooks:
- id: black
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.0.277
rev: v0.0.278
hooks:
- id: ruff
args: [--exit-non-zero-on-fix]
Expand All @@ -38,6 +38,15 @@ repos:
- id: codespell
types_or: [python, rst, markdown, cython, c]
additional_dependencies: [tomli]

- repo: https://github.com/adamchainz/blacken-docs
rev: 1.15.0
hooks:
- id: blacken-docs
additional_dependencies: [black==23.3.0]
files: '\.rst$'
args: [--skip-errors]

- repo: https://github.com/MarcoGorelli/cython-lint
rev: v0.15.0
hooks:
Expand Down Expand Up @@ -99,7 +108,7 @@ repos:
hooks:
- id: isort
- repo: https://github.com/asottile/pyupgrade
rev: v3.7.0
rev: v3.9.0
hooks:
- id: pyupgrade
args: [--py39-plus]
Expand Down
40 changes: 26 additions & 14 deletions doc/source/development/contributing_codebase.rst
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ the ``pandas.util._decorators.deprecate``:

from pandas.util._decorators import deprecate

deprecate('old_func', 'new_func', '1.1.0')
deprecate("old_func", "new_func", "1.1.0")

Otherwise, you need to do it manually:

Expand All @@ -135,7 +135,7 @@ Otherwise, you need to do it manually:
Use new_func instead.
"""
warnings.warn(
'Use new_func instead.',
"Use new_func instead.",
FutureWarning,
stacklevel=find_stack_level(),
)
Expand Down Expand Up @@ -179,6 +179,7 @@ The appropriate way to annotate this would be as follows

str_type = str


class SomeClass2:
str: str_type = None

Expand All @@ -190,8 +191,8 @@ In some cases you may be tempted to use ``cast`` from the typing module when you

from pandas.core.dtypes.common import is_number

def cannot_infer_bad(obj: Union[str, int, float]):

def cannot_infer_bad(obj: Union[str, int, float]):
if is_number(obj):
...
else: # Reasonably only str objects would reach this but...
Expand All @@ -203,7 +204,6 @@ The limitation here is that while a human can reasonably understand that ``is_nu
.. code-block:: python

def cannot_infer_good(obj: Union[str, int, float]):

if isinstance(obj, str):
return obj.upper()
else:
Expand All @@ -222,6 +222,7 @@ For example, quite a few functions in pandas accept a ``dtype`` argument. This c

from pandas._typing import Dtype


def as_type(dtype: Dtype) -> ...:
...

Expand Down Expand Up @@ -428,6 +429,7 @@ be located.
import pandas as pd
import pandas._testing as tm


def test_getitem_listlike_of_ints():
ser = pd.Series(range(5))

Expand Down Expand Up @@ -638,25 +640,29 @@ as a comment to a new test.
import pandas as pd


@pytest.mark.parametrize('dtype', ['int8', 'int16', 'int32', 'int64'])
@pytest.mark.parametrize("dtype", ["int8", "int16", "int32", "int64"])
def test_dtypes(dtype):
assert str(np.dtype(dtype)) == dtype


@pytest.mark.parametrize(
'dtype', ['float32', pytest.param('int16', marks=pytest.mark.skip),
pytest.param('int32', marks=pytest.mark.xfail(
reason='to show how it works'))])
"dtype",
[
"float32",
pytest.param("int16", marks=pytest.mark.skip),
pytest.param("int32", marks=pytest.mark.xfail(reason="to show how it works")),
],
)
def test_mark(dtype):
assert str(np.dtype(dtype)) == 'float32'
assert str(np.dtype(dtype)) == "float32"


@pytest.fixture
def series():
return pd.Series([1, 2, 3])


@pytest.fixture(params=['int8', 'int16', 'int32', 'int64'])
@pytest.fixture(params=["int8", "int16", "int32", "int64"])
def dtype(request):
return request.param

Expand Down Expand Up @@ -725,10 +731,16 @@ for details <https://hypothesis.readthedocs.io/en/latest/index.html>`_.
import json
from hypothesis import given, strategies as st

any_json_value = st.deferred(lambda: st.one_of(
st.none(), st.booleans(), st.floats(allow_nan=False), st.text(),
st.lists(any_json_value), st.dictionaries(st.text(), any_json_value)
))
any_json_value = st.deferred(
lambda: st.one_of(
st.none(),
st.booleans(),
st.floats(allow_nan=False),
st.text(),
st.lists(any_json_value),
st.dictionaries(st.text(), any_json_value),
)
)


@given(value=any_json_value)
Expand Down
10 changes: 3 additions & 7 deletions doc/source/development/contributing_docstring.rst
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,6 @@ backticks. The following are considered inline code:
.. code-block:: python

def func():

"""Some function.

With several mistakes in the docstring.
Expand Down Expand Up @@ -297,7 +296,7 @@ would be used, then we will specify "str, int or None, default None".
.. code-block:: python

class Series:
def plot(self, kind, color='blue', **kwargs):
def plot(self, kind, color="blue", **kwargs):
"""
Generate a plot.

Expand Down Expand Up @@ -463,6 +462,7 @@ With more than one value:

import string


def random_letters():
"""
Generate and return a sequence of random letters.
Expand All @@ -478,8 +478,7 @@ With more than one value:
String of random letters.
"""
length = np.random.randint(1, 10)
letters = ''.join(np.random.choice(string.ascii_lowercase)
for i in range(length))
letters = "".join(np.random.choice(string.ascii_lowercase) for i in range(length))
return length, letters

If the method yields its value:
Expand Down Expand Up @@ -628,7 +627,6 @@ A simple example could be:
.. code-block:: python

class Series:

def head(self, n=5):
"""
Return the first elements of the Series.
Expand Down Expand Up @@ -724,7 +722,6 @@ positional arguments ``head(3)``.
.. code-block:: python

class Series:

def mean(self):
"""
Compute the mean of the input.
Expand All @@ -737,7 +734,6 @@ positional arguments ``head(3)``.
"""
pass


def fillna(self, value):
"""
Replace missing values by ``value``.
Expand Down
6 changes: 3 additions & 3 deletions doc/source/development/contributing_documentation.rst
Original file line number Diff line number Diff line change
Expand Up @@ -62,9 +62,9 @@ Some other important things to know about the docs:

will be rendered as::

In [1]: x = 2
In[1]: x = 2

In [2]: x**3
In[2]: x**3
Out[2]: 8

Almost all code examples in the docs are run (and the output saved) during the
Expand Down Expand Up @@ -191,7 +191,7 @@ to speed up the documentation build. You can override this::
Open the following file in a web browser to see the full documentation you
just built::

doc/build/html/index.html
doc / build / html / index.html

And you'll have the satisfaction of seeing your new and improved documentation!

Expand Down
2 changes: 1 addition & 1 deletion doc/source/development/extending.rst
Original file line number Diff line number Diff line change
Expand Up @@ -408,7 +408,6 @@ Below is an example to define two original properties, "internal_cache" as a tem
.. code-block:: python

class SubclassedDataFrame2(pd.DataFrame):

# temporary properties
_internal_names = pd.DataFrame._internal_names + ["internal_cache"]
_internal_names_set = set(_internal_names)
Expand Down Expand Up @@ -526,6 +525,7 @@ The ``__pandas_priority__`` of :class:`DataFrame`, :class:`Series`, and :class:`
# return `self` and not the addition for simplicity
return self


custom = CustomList()
series = pd.Series([1, 2, 3])

Expand Down
1 change: 1 addition & 0 deletions doc/source/development/maintaining.rst
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,7 @@ create a file ``t.py`` in your pandas directory, which contains
.. code-block:: python

import pandas as pd

assert pd.Series([1, 1]).sum() == 2

and then run::
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -427,9 +427,7 @@ The equivalent in pandas:

.. ipython:: python

pd.pivot_table(
tips, values="tip", index=["size"], columns=["sex"], aggfunc=np.average
)
pd.pivot_table(tips, values="tip", index=["size"], columns=["sex"], aggfunc=np.average)


Adding a row
Expand All @@ -440,8 +438,9 @@ Assuming we are using a :class:`~pandas.RangeIndex` (numbered ``0``, ``1``, etc.
.. ipython:: python

df
new_row = pd.DataFrame([["E", 51, True]],
columns=["class", "student_count", "all_pass"])
new_row = pd.DataFrame(
[["E", 51, True]], columns=["class", "student_count", "all_pass"]
)
pd.concat([df, new_row])


Expand Down
12 changes: 3 additions & 9 deletions doc/source/getting_started/comparison/comparison_with_sql.rst
Original file line number Diff line number Diff line change
Expand Up @@ -331,9 +331,7 @@ UNION
df1 = pd.DataFrame(
{"city": ["Chicago", "San Francisco", "New York City"], "rank": range(1, 4)}
)
df2 = pd.DataFrame(
{"city": ["Chicago", "Boston", "Los Angeles"], "rank": [1, 4, 5]}
)
df2 = pd.DataFrame({"city": ["Chicago", "Boston", "Los Angeles"], "rank": [1, 4, 5]})

.. code-block:: sql

Expand Down Expand Up @@ -433,9 +431,7 @@ Top n rows per group

(
tips.assign(
rn=tips.sort_values(["total_bill"], ascending=False)
.groupby(["day"])
.cumcount()
rn=tips.sort_values(["total_bill"], ascending=False).groupby(["day"]).cumcount()
+ 1
)
.query("rn < 3")
Expand All @@ -448,9 +444,7 @@ the same using ``rank(method='first')`` function

(
tips.assign(
rnk=tips.groupby(["day"])["total_bill"].rank(
method="first", ascending=False
)
rnk=tips.groupby(["day"])["total_bill"].rank(method="first", ascending=False)
)
.query("rnk < 3")
.sort_values(["day", "rnk"])
Expand Down
10 changes: 4 additions & 6 deletions doc/source/getting_started/comparison/includes/time_date.rst
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,11 @@
tips["date1_year"] = tips["date1"].dt.year
tips["date2_month"] = tips["date2"].dt.month
tips["date1_next"] = tips["date1"] + pd.offsets.MonthBegin()
tips["months_between"] = tips["date2"].dt.to_period("M") - tips[
"date1"
].dt.to_period("M")
tips["months_between"] = tips["date2"].dt.to_period("M") - tips["date1"].dt.to_period(
"M"
)

tips[
["date1", "date2", "date1_year", "date2_month", "date1_next", "months_between"]
]
tips[["date1", "date2", "date1_year", "date2_month", "date1_next", "months_between"]]

.. ipython:: python
:suppress:
Expand Down
1 change: 1 addition & 0 deletions doc/source/getting_started/install.rst
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,7 @@ libraries. Python internally has a list of directories it searches through, to f
obtain these directories with::

import sys

sys.path

One way you could be encountering this error is if you have multiple Python installations on your system
Expand Down
14 changes: 9 additions & 5 deletions doc/source/getting_started/intro_tutorials/04_plotting.rst
Original file line number Diff line number Diff line change
Expand Up @@ -218,11 +218,15 @@ This strategy is applied in the previous example:

::

fig, axs = plt.subplots(figsize=(12, 4)) # Create an empty Matplotlib Figure and Axes
air_quality.plot.area(ax=axs) # Use pandas to put the area plot on the prepared Figure/Axes
axs.set_ylabel("NO$_2$ concentration") # Do any Matplotlib customization you like
fig.savefig("no2_concentrations.png") # Save the Figure/Axes using the existing Matplotlib method.
plt.show() # Display the plot
fig, axs = plt.subplots(figsize=(12, 4)) # Create an empty Matplotlib Figure and Axes
air_quality.plot.area(
ax=axs
) # Use pandas to put the area plot on the prepared Figure/Axes
axs.set_ylabel("NO$_2$ concentration") # Do any Matplotlib customization you like
fig.savefig(
"no2_concentrations.png"
) # Save the Figure/Axes using the existing Matplotlib method.
plt.show() # Display the plot

.. raw:: html

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ I want to sort the Titanic data according to the cabin class and age in descendi

.. ipython:: python

titanic.sort_values(by=['Pclass', 'Age'], ascending=False).head()
titanic.sort_values(by=["Pclass", "Age"], ascending=False).head()

With :meth:`DataFrame.sort_values`, the rows in the table are sorted according to the
defined column(s). The index will follow the row order.
Expand Down
Loading