Skip to content

Commit

Permalink
Use ruff to format code snippets in docstrings and remove blackdoc (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
seisman authored Dec 27, 2023
1 parent 94e4598 commit fbc4e97
Show file tree
Hide file tree
Showing 21 changed files with 25 additions and 85 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/format-command.yml
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ jobs:
# Install formatting tools
- name: Install formatting tools
run: |
python -m pip install blackdoc docformatter ruff
python -m pip install docformatter ruff
python -m pip list
sudo apt-get install dos2unix
Expand Down
4 changes: 2 additions & 2 deletions .github/workflows/style_checks.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -34,11 +34,11 @@ jobs:

- name: Install packages
run: |
python -m pip install blackdoc docformatter ruff
python -m pip install docformatter ruff
python -m pip list
sudo apt-get install dos2unix
- name: Formatting check (blackdoc, docformatter, ruff)
- name: Formatting check (docformatter, ruff)
run: make check

- name: Ensure files use UNIX line breaks and have 644 permission
Expand Down
6 changes: 2 additions & 4 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ help:
@echo " fulltest run the test suite (including all doctests)"
@echo " doctest run the doctests only"
@echo " test_no_images run the test suite (including all doctests) but skip image comparisons"
@echo " format run blackdoc, docformatter and ruff to automatically format the code"
@echo " check run code style and quality checks (blackdoc, docformatter, ruff)"
@echo " format run docformatter and ruff to automatically format the code"
@echo " check run code style and quality checks (docformatter and ruff)"
@echo " codespell run codespell to check common misspellings"
@echo " typecheck run mypy for static type check"
@echo " clean clean up build and generated files"
Expand Down Expand Up @@ -61,13 +61,11 @@ test_no_images: _runtest

format:
docformatter --in-place $(FORMAT_FILES)
blackdoc $(FORMAT_FILES)
ruff check --fix $(FORMAT_FILES)
ruff format $(FORMAT_FILES)

check:
docformatter --check $(FORMAT_FILES)
blackdoc --check $(FORMAT_FILES)
ruff check $(FORMAT_FILES)
ruff format --check $(FORMAT_FILES)

Expand Down
3 changes: 1 addition & 2 deletions doc/contributing.md
Original file line number Diff line number Diff line change
Expand Up @@ -473,7 +473,6 @@ code, be sure to follow the general guidelines in the

We use some tools to format the code so we don't have to think about it:

- [blackdoc](https://github.com/keewis/blackdoc)
- [docformatter](https://github.com/myint/docformatter)
- [ruff](https://docs.astral.sh/ruff)

Expand Down Expand Up @@ -512,7 +511,7 @@ The [`Makefile`](https://github.com/GenericMappingTools/pygmt/blob/main/Makefile
contains rules for running the linter checks:

```bash
make check # Runs blackdoc, docformatter, ruff (in check mode)
make check # Runs docformatter and ruff (in check mode)
```

### Testing your Code
Expand Down
3 changes: 1 addition & 2 deletions environment.yml
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,9 @@ dependencies:
- make
- pip
# Dev dependencies (style checks)
- blackdoc
- codespell
- docformatter>=1.7.2
- ruff
- ruff>=0.1.9
# Dev dependencies (unit testing)
- matplotlib
- pytest-cov
Expand Down
4 changes: 1 addition & 3 deletions pygmt/accessors.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,9 +57,7 @@ class GMTDataArrayAccessor:
>>> lon = np.arange(0, 360 + interval, interval)
>>> longrid, latgrid = np.meshgrid(lon, lat)
>>> data = np.sin(np.deg2rad(longrid)) * np.cos(np.deg2rad(latgrid))
>>> grid = xr.DataArray(
... data, coords=[("latitude", lat), ("longitude", lon)]
... )
>>> grid = xr.DataArray(data, coords=[("latitude", lat), ("longitude", lon)])
>>> # default to a gridline-registrated Cartesian grid
>>> grid.gmt.registration, grid.gmt.gtype
(0, 0)
Expand Down
26 changes: 3 additions & 23 deletions pygmt/clib/session.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,6 @@ class Session:
... ses.call_module("grdinfo", f"{fin} -C ->{fout.name}")
... # Read the contents of the temp file before it's deleted.
... print(fout.read().strip())
...
-55 -47 -24 -10 190 981 1 1 8 14 1 1
"""

Expand Down Expand Up @@ -305,7 +304,6 @@ def get_libgmt_func(self, name, argtypes=None, restype=None):
... func = lib.get_libgmt_func(
... "GMT_Destroy_Session", argtypes=[c_void_p], restype=c_int
... )
...
>>> type(func)
<class 'ctypes.CDLL.__init__.<locals>._FuncPtr'>
"""
Expand Down Expand Up @@ -546,13 +544,11 @@ def get_common(self, option):
... lib.call_module("plot", "-T -Xw+1i -Yh-1i")
... xshift = lib.get_common("X") # xshift/yshift are in inches
... yshift = lib.get_common("Y")
...
>>> print(region, projection, timestamp, verbose, xshift, yshift)
[ 0. 10. 10. 15.] True False 3 6.0 1.5
>>> with Session() as lib:
... lib.call_module("basemap", "-R0/10/10/15 -JX5i/2.5i -Baf")
... lib.get_common("A")
...
Traceback (most recent call last):
...
pygmt.exceptions.GMTInvalidInput: Unknown GMT common option flag 'A'.
Expand Down Expand Up @@ -816,13 +812,11 @@ def _check_dtype_and_dim(self, array, ndim):
>>> with Session() as ses:
... gmttype = ses._check_dtype_and_dim(data, ndim=1)
... gmttype == ses["GMT_DOUBLE"]
...
True
>>> data = np.ones((5, 2), dtype="float32")
>>> with Session() as ses:
... gmttype = ses._check_dtype_and_dim(data, ndim=2)
... gmttype == ses["GMT_FLOAT"]
...
True
"""
# Check that the array has the given number of dimensions
Expand Down Expand Up @@ -1150,7 +1144,6 @@ def open_virtual_file(self, family, geometry, direction, data):
... args = f"{vfile} ->{ofile.name}"
... lib.call_module("info", args)
... print(ofile.read().strip())
...
<vector memory>: N = 5 <0/4> <5/9>
"""
c_open_virtualfile = self.get_libgmt_func(
Expand Down Expand Up @@ -1241,7 +1234,6 @@ def virtualfile_from_vectors(self, *vectors):
... with GMTTempFile() as fout:
... ses.call_module("info", f"{fin} ->{fout.name}")
... print(fout.read().strip())
...
<vector memory>: N = 3 <1/3> <4/6> <7/9>
"""
# Conversion to a C-contiguous array needs to be done here and not in
Expand Down Expand Up @@ -1350,7 +1342,6 @@ def virtualfile_from_matrix(self, matrix):
... with GMTTempFile() as fout:
... ses.call_module("info", f"{fin} ->{fout.name}")
... print(fout.read().strip())
...
<matrix memory>: N = 4 <0/9> <1/10> <2/11>
"""
# Conversion to a C-contiguous array needs to be done here and not in
Expand Down Expand Up @@ -1432,7 +1423,6 @@ def virtualfile_from_grid(self, grid):
... args = f"{fin} -L0 -Cn ->{fout.name}"
... ses.call_module("grdinfo", args)
... print(fout.read().strip())
...
-55 -47 -24 -10 190 981 1 1 8 14 1 1
>>> # The output is: w e s n z0 z1 dx dy n_columns n_rows reg gtype
"""
Expand Down Expand Up @@ -1520,14 +1510,11 @@ def virtualfile_from_data( # noqa: PLR0912
... ),
... )
>>> with Session() as ses:
... with ses.virtualfile_from_data(
... check_kind="vector", data=data
... ) as fin:
... with ses.virtualfile_from_data(check_kind="vector", data=data) as fin:
... # Send the output to a file so that we can read it
... with GMTTempFile() as fout:
... ses.call_module("info", fin + " ->" + fout.name)
... print(fout.read().strip())
...
<vector memory>: N = 3 <7/9> <4/6> <1/3>
"""
kind = data_kind(
Expand Down Expand Up @@ -1623,20 +1610,16 @@ def extract_region(self):
... )
>>> with Session() as lib:
... wesn = lib.extract_region()
...
>>> print(", ".join([f"{x:.2f}" for x in wesn]))
0.00, 10.00, -20.00, -10.00
Using ISO country codes for the regions (for example ``"US.HI"`` for
Hawaiʻi):
>>> fig = pygmt.Figure()
>>> fig.coast(
... region="US.HI", projection="M6i", frame=True, land="black"
... )
>>> fig.coast(region="US.HI", projection="M6i", frame=True, land="black")
>>> with Session() as lib:
... wesn = lib.extract_region()
...
>>> print(", ".join([f"{x:.2f}" for x in wesn]))
-164.71, -154.81, 18.91, 23.58
Expand All @@ -1645,12 +1628,9 @@ def extract_region(self):
region to multiples of 5):
>>> fig = pygmt.Figure()
>>> fig.coast(
... region="US.HI+r5", projection="M6i", frame=True, land="black"
... )
>>> fig.coast(region="US.HI+r5", projection="M6i", frame=True, land="black")
>>> with Session() as lib:
... wesn = lib.extract_region()
...
>>> print(", ".join([f"{x:.2f}" for x in wesn]))
-165.00, -150.00, 15.00, 25.00
""" # noqa: RUF002
Expand Down
4 changes: 1 addition & 3 deletions pygmt/datasets/earth_free_air_anomaly.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,9 +92,7 @@ def load_earth_free_air_anomaly(
>>> # load the default grid (gridline-registered 1 arc-degree grid)
>>> grid = load_earth_free_air_anomaly()
>>> # load the 30 arc-minutes grid with "gridline" registration
>>> grid = load_earth_free_air_anomaly(
... resolution="30m", registration="gridline"
... )
>>> grid = load_earth_free_air_anomaly(resolution="30m", registration="gridline")
>>> # load high-resolution (5 arc-minutes) grid for a specific region
>>> grid = load_earth_free_air_anomaly(
... resolution="05m",
Expand Down
4 changes: 1 addition & 3 deletions pygmt/datasets/earth_magnetic_anomaly.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,9 +119,7 @@ def load_earth_magnetic_anomaly(
>>> # load the default grid (gridline-registered 1 arc-degree grid)
>>> grid = load_earth_magnetic_anomaly()
>>> # load the 30 arc-minutes grid with "gridline" registration
>>> grid = load_earth_magnetic_anomaly(
... resolution="30m", registration="gridline"
... )
>>> grid = load_earth_magnetic_anomaly(resolution="30m", registration="gridline")
>>> # load high-resolution (5 arc-minutes) grid for a specific region
>>> grid = load_earth_magnetic_anomaly(
... resolution="05m",
Expand Down
9 changes: 1 addition & 8 deletions pygmt/helpers/decorators.py
Original file line number Diff line number Diff line change
Expand Up @@ -421,7 +421,6 @@ def fmt_docstring(module_func):
... {aliases}
... '''
... pass
...
>>> print(gmtinfo.__doc__)
<BLANKLINE>
My nice module.
Expand Down Expand Up @@ -526,7 +525,6 @@ def use_alias(**aliases):
>>> @use_alias(R="region", J="projection")
... def my_module(**kwargs):
... print("R =", kwargs["R"], "J =", kwargs["J"])
...
>>> my_module(R="bla", J="meh")
R = bla J = meh
>>> my_module(region="bla", J="meh")
Expand Down Expand Up @@ -641,9 +639,7 @@ def kwargs_to_strings(**conversions):
Examples
--------
>>> @kwargs_to_strings(
... R="sequence", i="sequence_comma", files="sequence_space"
... )
>>> @kwargs_to_strings(R="sequence", i="sequence_comma", files="sequence_space")
... def module(*args, **kwargs):
... "A module that prints the arguments it received"
... print("{", end="")
Expand Down Expand Up @@ -813,7 +809,6 @@ def deprecate_parameter(oldname, newname, deprecate_version, remove_version):
... def module(data, size=0, **kwargs):
... "A module that prints the arguments it received"
... print(f"data={data}, size={size}, color={kwargs['color']}")
...
>>> # new names are supported
>>> module(data="table.txt", size=5.0, color="red")
data=table.txt, size=5.0, color=red
Expand All @@ -825,13 +820,11 @@ def deprecate_parameter(oldname, newname, deprecate_version, remove_version):
... for i in range(len(w)):
... assert issubclass(w[i].category, FutureWarning)
... assert "deprecated" in str(w[i].message)
...
data=table.txt, size=5.0, color=red
>>> # using both old and new names will raise an GMTInvalidInput exception
>>> import pytest
>>> with pytest.raises(GMTInvalidInput):
... module(data="table.txt", size=5.0, sizes=4.0)
...
"""

def deprecator(module_func):
Expand Down
1 change: 0 additions & 1 deletion pygmt/helpers/tempfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,6 @@ class GMTTempFile:
... print(lines)
... nx, ny, nz = tmpfile.loadtxt(unpack=True, dtype=float)
... print(nx, ny, nz)
...
0.0 1.0 2.0
0.0 1.0 2.0
0.0 1.0 2.0
Expand Down
4 changes: 0 additions & 4 deletions pygmt/helpers/testing.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,6 @@ def check_figures_equal(*, extensions=("png",), tol=0.0, result_dir="result_imag
... projection="X5c", region=[0, 5, 0, 5], frame=["WrStZ", "af"]
... )
... return fig_ref, fig_test
...
>>> test_check_figures_equal()
>>> assert len(os.listdir("tmp_result_images")) == 0
>>> shutil.rmtree(path="tmp_result_images") # cleanup folder if tests pass
Expand All @@ -60,18 +59,15 @@ def check_figures_equal(*, extensions=("png",), tol=0.0, result_dir="result_imag
... fig_test = Figure()
... fig_test.basemap(projection="X5c", region=[0, 3, 0, 3], frame=True)
... return fig_ref, fig_test
...
>>> with pytest.raises(GMTImageComparisonFailure):
... test_check_figures_unequal()
...
>>> for suffix in ["", "-expected", "-failed-diff"]:
... assert os.path.exists(
... os.path.join(
... "tmp_result_images",
... f"test_check_figures_unequal{suffix}.png",
... )
... )
...
>>> shutil.rmtree(path="tmp_result_images") # cleanup folder if tests pass
"""
allowed_chars = set(string.digits + string.ascii_letters + "_-[]()")
Expand Down
8 changes: 2 additions & 6 deletions pygmt/src/blockm.py
Original file line number Diff line number Diff line change
Expand Up @@ -156,9 +156,7 @@ def blockmean(data=None, x=None, y=None, z=None, outfile=None, **kwargs):
>>> # Load a table of ship observations of bathymetry off Baja California
>>> data = pygmt.datasets.load_sample_data(name="bathymetry")
>>> # Calculate block mean values within 5 by 5 arc-minute bins
>>> data_bmean = pygmt.blockmean(
... data=data, region=[245, 255, 20, 30], spacing="5m"
... )
>>> data_bmean = pygmt.blockmean(data=data, region=[245, 255, 20, 30], spacing="5m")
"""
return _blockm(
block_method="blockmean", data=data, x=x, y=y, z=z, outfile=outfile, **kwargs
Expand Down Expand Up @@ -330,9 +328,7 @@ def blockmode(data=None, x=None, y=None, z=None, outfile=None, **kwargs):
>>> # Load a table of ship observations of bathymetry off Baja California
>>> data = pygmt.datasets.load_sample_data(name="bathymetry")
>>> # Calculate block mode values within 5 by 5 arc-minute bins
>>> data_bmode = pygmt.blockmode(
... data=data, region=[245, 255, 20, 30], spacing="5m"
... )
>>> data_bmode = pygmt.blockmode(data=data, region=[245, 255, 20, 30], spacing="5m")
"""
return _blockm(
block_method="blockmode", data=data, x=x, y=y, z=z, outfile=outfile, **kwargs
Expand Down
4 changes: 1 addition & 3 deletions pygmt/src/grdclip.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,9 +90,7 @@ def grdclip(grid, **kwargs):
[170.0, 2275.5]
>>> # Create a new grid from an input grid. Set all values below 1,000 to
>>> # 0 and all values above 1,500 to 10,000
>>> new_grid = pygmt.grdclip(
... grid=grid, below=[1000, 0], above=[1500, 10000]
... )
>>> new_grid = pygmt.grdclip(grid=grid, below=[1000, 0], above=[1500, 10000])
>>> # Report the minimum and maximum data values
>>> [new_grid.data.min(), new_grid.data.max()]
[0.0, 10000.0]
Expand Down
4 changes: 1 addition & 3 deletions pygmt/src/grdfill.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,9 +70,7 @@ def grdfill(grid, **kwargs):
-------
>>> import pygmt
>>> # Load a bathymetric grid with missing data
>>> earth_relief_holes = pygmt.datasets.load_sample_data(
... name="earth_relief_holes"
... )
>>> earth_relief_holes = pygmt.datasets.load_sample_data(name="earth_relief_holes")
>>> # Perform grid filling operations on the sample grid
>>> # Set all empty values to "20"
>>> filled_grid = pygmt.grdfill(grid=earth_relief_holes, mode="c20")
Expand Down
4 changes: 1 addition & 3 deletions pygmt/src/grdsample.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,9 +85,7 @@ def grdsample(grid, **kwargs):
... )
>>> # Create a new grid from an input grid, change the registration,
>>> # and set both x- and y-spacing to 0.5 arc-degrees
>>> new_grid = pygmt.grdsample(
... grid=grid, translate=True, spacing=[0.5, 0.5]
... )
>>> new_grid = pygmt.grdsample(grid=grid, translate=True, spacing=[0.5, 0.5])
"""
with GMTTempFile(suffix=".nc") as tmpfile:
with Session() as lib:
Expand Down
1 change: 0 additions & 1 deletion pygmt/src/meca.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,6 @@ def convention_code(convention, component="full"):
>>> for code in ["a", "c", "m", "d", "z", "p", "x", "y", "t"]:
... assert convention_code(code) == code
...
>>> convention_code("invalid")
Traceback (most recent call last):
Expand Down
4 changes: 1 addition & 3 deletions pygmt/src/solar.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,9 +72,7 @@ def solar(self, terminator="d", terminator_datetime=None, **kwargs):
>>> # create a new plot with pygmt.Figure()
>>> fig = pygmt.Figure()
>>> # create a map of the Earth with the coast method
>>> fig.coast(
... land="darkgreen", water="lightblue", projection="W10c", region="d"
... )
>>> fig.coast(land="darkgreen", water="lightblue", projection="W10c", region="d")
>>> fig.solar(
... # set the terminator to "day_night"
... terminator="day_night",
Expand Down
Loading

0 comments on commit fbc4e97

Please sign in to comment.