Skip to content

Commit 1bf0a30

Browse files
authored
Add blackdoc to format Python codes in docstrings (#641)
* Add blackdoc to format Python codes in docstrings * Run "makeformat" to format codes in docstrings
1 parent c191d3e commit 1bf0a30

12 files changed

+93
-69
lines changed

.github/workflows/ci_tests.yaml

+1-1
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ jobs:
2828
python-version: 3.7
2929

3030
- name: Install packages
31-
run: pip install black flake8 pylint
31+
run: pip install black blackdoc flake8 pylint
3232

3333
- name: Formatting check (black and flake8)
3434
run: make check

CONTRIBUTING.md

+3-3
Original file line numberDiff line numberDiff line change
@@ -245,8 +245,8 @@ directory).
245245

246246
### Code style
247247

248-
We use [Black](https://github.com/ambv/black) to format the code so we don't have to
249-
think about it.
248+
We use [Black](https://github.com/ambv/black) and [blackdoc](https://github.com/keewis/blackdoc)
249+
to format the code so we don't have to think about it.
250250
Black loosely follows the [PEP8](http://pep8.org) guide but with a few differences.
251251
Regardless, you won't have to worry about formatting the code yourself.
252252
Before committing, run it to automatically format your code:
@@ -265,7 +265,7 @@ common errors.
265265
The [`Makefile`](Makefile) contains rules for running both checks:
266266

267267
```bash
268-
make check # Runs flake8 and black (in check mode)
268+
make check # Runs flake8, black and blackdoc (in check mode)
269269
make lint # Runs pylint, which is a bit slower
270270
```
271271

Makefile

+5-2
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ PYTEST_ARGS=--cov=$(PROJECT) --cov-config=../.coveragerc \
66
--doctest-modules -v --mpl --mpl-results-path=results \
77
--pyargs ${PYTEST_EXTRA}
88
BLACK_FILES=$(PROJECT) setup.py doc/conf.py examples
9+
BLACKDOC_OPTIONS=--line-length 79
910
FLAKE8_FILES=$(PROJECT) setup.py doc/conf.py
1011
LINT_FILES=$(PROJECT) setup.py doc/conf.py
1112

@@ -14,8 +15,8 @@ help:
1415
@echo ""
1516
@echo " install install in editable mode"
1617
@echo " test run the test suite (including doctests) and report coverage"
17-
@echo " format run black to automatically format the code"
18-
@echo " check run code style and quality checks (black and flake8)"
18+
@echo " format run black and blackdoc to automatically format the code"
19+
@echo " check run code style and quality checks (black, blackdoc and flake8)"
1920
@echo " lint run pylint for a deeper (and slower) quality check"
2021
@echo " clean clean up build and generated files"
2122
@echo ""
@@ -36,9 +37,11 @@ test:
3637

3738
format:
3839
black $(BLACK_FILES)
40+
blackdoc $(BLACKDOC_OPTIONS) $(BLACK_FILES)
3941

4042
check:
4143
black --check $(BLACK_FILES)
44+
blackdoc --check $(BLACKDOC_OPTIONS) $(BLACK_FILES)
4245
flake8 $(FLAKE8_FILES)
4346

4447
lint:

environment.yml

+1
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ dependencies:
1919
- pytest-mpl
2020
- coverage
2121
- black
22+
- blackdoc
2223
- pylint
2324
- flake8
2425
- sphinx=2.2.1

pygmt/base_plotting.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ def _preprocess(self, **kwargs): # pylint: disable=no-self-use
4848
--------
4949
5050
>>> base = BasePlotting()
51-
>>> base._preprocess(resolution='low')
51+
>>> base._preprocess(resolution="low")
5252
{'resolution': 'low'}
5353
5454
"""

pygmt/clib/conversion.py

+9-8
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ def dataarray_to_matrix(grid):
4747
4848
>>> from pygmt.datasets import load_earth_relief
4949
>>> # Use the global Earth relief grid with 1 degree spacing
50-
>>> grid = load_earth_relief(resolution='01d')
50+
>>> grid = load_earth_relief(resolution="01d")
5151
>>> matrix, region, inc = dataarray_to_matrix(grid)
5252
>>> print(region)
5353
[-180.0, 180.0, -90.0, 90.0]
@@ -61,7 +61,7 @@ def dataarray_to_matrix(grid):
6161
True
6262
>>> # Using a slice of the grid, the matrix will be copied to guarantee
6363
>>> # that it's C-contiguous in memory. The increment should be unchanged.
64-
>>> matrix, region, inc = dataarray_to_matrix(grid[10:41,30:101])
64+
>>> matrix, region, inc = dataarray_to_matrix(grid[10:41, 30:101])
6565
>>> matrix.flags.c_contiguous
6666
True
6767
>>> print(matrix.shape)
@@ -71,7 +71,7 @@ def dataarray_to_matrix(grid):
7171
>>> print(inc)
7272
[1.0, 1.0]
7373
>>> # but not if only taking every other grid point.
74-
>>> matrix, region, inc = dataarray_to_matrix(grid[10:41:2,30:101:2])
74+
>>> matrix, region, inc = dataarray_to_matrix(grid[10:41:2, 30:101:2])
7575
>>> matrix.flags.c_contiguous
7676
True
7777
>>> print(matrix.shape)
@@ -231,11 +231,12 @@ def kwargs_to_ctypes_array(argument, kwargs, dtype):
231231
--------
232232
233233
>>> import ctypes as ct
234-
>>> value = kwargs_to_ctypes_array('bla', {'bla': [10, 10]}, ct.c_long*2)
234+
>>> value = kwargs_to_ctypes_array("bla", {"bla": [10, 10]}, ct.c_long * 2)
235235
>>> type(value)
236236
<class 'pygmt.clib.conversion.c_long_Array_2'>
237237
>>> should_be_none = kwargs_to_ctypes_array(
238-
... 'swallow', {'bla': 1, 'foo': [20, 30]}, ct.c_int*2)
238+
... "swallow", {"bla": 1, "foo": [20, 30]}, ct.c_int * 2
239+
... )
239240
>>> print(should_be_none)
240241
None
241242
@@ -313,9 +314,9 @@ def array_to_datetime(array):
313314
314315
>>> # Mixed datetime types
315316
>>> x = [
316-
... "2018-01-01",
317-
... np.datetime64("2018-01-01"),
318-
... datetime.datetime(2018, 1, 1),
317+
... "2018-01-01",
318+
... np.datetime64("2018-01-01"),
319+
... datetime.datetime(2018, 1, 1),
319320
... ]
320321
>>> array_to_datetime(x) # doctest: +NORMALIZE_WHITESPACE
321322
DatetimeIndex(['2018-01-01', '2018-01-01', '2018-01-01'],

pygmt/clib/session.py

+32-25
Original file line numberDiff line numberDiff line change
@@ -270,8 +270,9 @@ def get_libgmt_func(self, name, argtypes=None, restype=None):
270270
271271
>>> from ctypes import c_void_p, c_int
272272
>>> with Session() as lib:
273-
... func = lib.get_libgmt_func('GMT_Destroy_Session',
274-
... argtypes=[c_void_p], restype=c_int)
273+
... func = lib.get_libgmt_func(
274+
... "GMT_Destroy_Session", argtypes=[c_void_p], restype=c_int
275+
... )
275276
>>> type(func)
276277
<class 'ctypes.CDLL.__init__.<locals>._FuncPtr'>
277278
@@ -702,15 +703,15 @@ def _check_dtype_and_dim(self, array, ndim):
702703
--------
703704
704705
>>> import numpy as np
705-
>>> data = np.array([1, 2, 3], dtype='float64')
706+
>>> data = np.array([1, 2, 3], dtype="float64")
706707
>>> with Session() as ses:
707708
... gmttype = ses._check_dtype_and_dim(data, ndim=1)
708709
... gmttype == ses["GMT_DOUBLE"]
709710
True
710-
>>> data = np.ones((5, 2), dtype='float32')
711+
>>> data = np.ones((5, 2), dtype="float32")
711712
>>> with Session() as ses:
712713
... gmttype = ses._check_dtype_and_dim(data, ndim=2)
713-
... gmttype == ses['GMT_FLOAT']
714+
... gmttype == ses["GMT_FLOAT"]
714715
True
715716
716717
"""
@@ -1022,23 +1023,23 @@ def open_virtual_file(self, family, geometry, direction, data):
10221023
>>> x = np.array([0, 1, 2, 3, 4])
10231024
>>> y = np.array([5, 6, 7, 8, 9])
10241025
>>> with Session() as lib:
1025-
... family = 'GMT_IS_DATASET|GMT_VIA_VECTOR'
1026-
... geometry = 'GMT_IS_POINT'
1026+
... family = "GMT_IS_DATASET|GMT_VIA_VECTOR"
1027+
... geometry = "GMT_IS_POINT"
10271028
... dataset = lib.create_data(
10281029
... family=family,
10291030
... geometry=geometry,
1030-
... mode='GMT_CONTAINER_ONLY',
1031+
... mode="GMT_CONTAINER_ONLY",
10311032
... dim=[2, 5, 1, 0], # columns, lines, segments, type
10321033
... )
10331034
... lib.put_vector(dataset, column=0, vector=x)
10341035
... lib.put_vector(dataset, column=1, vector=y)
10351036
... # Add the dataset to a virtual file
1036-
... vfargs = (family, geometry, 'GMT_IN|GMT_IS_REFERENCE', dataset)
1037+
... vfargs = (family, geometry, "GMT_IN|GMT_IS_REFERENCE", dataset)
10371038
... with lib.open_virtual_file(*vfargs) as vfile:
10381039
... # Send the output to a temp file so that we can read it
10391040
... with GMTTempFile() as ofile:
1040-
... args = '{} ->{}'.format(vfile, ofile.name)
1041-
... lib.call_module('info', args)
1041+
... args = "{} ->{}".format(vfile, ofile.name)
1042+
... lib.call_module("info", args)
10421043
... print(ofile.read().strip())
10431044
<vector memory>: N = 5 <0/4> <5/9>
10441045
@@ -1133,7 +1134,7 @@ def virtualfile_from_vectors(self, *vectors):
11331134
... # Send the output to a file so that we can read it
11341135
... with GMTTempFile() as fout:
11351136
... ses.call_module(
1136-
... 'info', '{} ->{}'.format(fin, fout.name)
1137+
... "info", "{} ->{}".format(fin, fout.name)
11371138
... )
11381139
... print(fout.read().strip())
11391140
<vector memory>: N = 3 <1/3> <4/6> <7/9>
@@ -1245,7 +1246,7 @@ def virtualfile_from_matrix(self, matrix):
12451246
... # Send the output to a file so that we can read it
12461247
... with GMTTempFile() as fout:
12471248
... ses.call_module(
1248-
... 'info', '{} ->{}'.format(fin, fout.name)
1249+
... "info", "{} ->{}".format(fin, fout.name)
12491250
... )
12501251
... print(fout.read().strip())
12511252
<matrix memory>: N = 4 <0/9> <1/10> <2/11>
@@ -1314,7 +1315,7 @@ def virtualfile_from_grid(self, grid):
13141315
13151316
>>> from pygmt.datasets import load_earth_relief
13161317
>>> from pygmt.helpers import GMTTempFile
1317-
>>> data = load_earth_relief(resolution='01d')
1318+
>>> data = load_earth_relief(resolution="01d")
13181319
>>> print(data.shape)
13191320
(180, 360)
13201321
>>> print(data.lon.values.min(), data.lon.values.max())
@@ -1327,8 +1328,8 @@ def virtualfile_from_grid(self, grid):
13271328
... with ses.virtualfile_from_grid(data) as fin:
13281329
... # Send the output to a file so that we can read it
13291330
... with GMTTempFile() as fout:
1330-
... args = '{} -L0 -Cn ->{}'.format(fin, fout.name)
1331-
... ses.call_module('grdinfo', args)
1331+
... args = "{} -L0 -Cn ->{}".format(fin, fout.name)
1332+
... ses.call_module("grdinfo", args)
13321333
... print(fout.read().strip())
13331334
-180 180 -90 90 -8182 5651.5 1 1 360 180 1 1
13341335
>>> # The output is: w e s n z0 z1 dx dy n_columns n_rows reg gtype
@@ -1378,34 +1379,40 @@ def extract_region(self):
13781379
13791380
>>> import pygmt
13801381
>>> fig = pygmt.Figure()
1381-
>>> fig.coast(region=[0, 10, -20, -10], projection="M6i", frame=True,
1382-
... land='black')
1382+
>>> fig.coast(
1383+
... region=[0, 10, -20, -10],
1384+
... projection="M6i",
1385+
... frame=True,
1386+
... land="black",
1387+
... )
13831388
>>> with Session() as lib:
13841389
... wesn = lib.extract_region()
1385-
>>> print(', '.join(['{:.2f}'.format(x) for x in wesn]))
1390+
>>> print(", ".join(["{:.2f}".format(x) for x in wesn]))
13861391
0.00, 10.00, -20.00, -10.00
13871392
13881393
Using ISO country codes for the regions (for example ``'US.HI'`` for
13891394
Hawaii):
13901395
13911396
>>> fig = pygmt.Figure()
1392-
>>> fig.coast(region='US.HI', projection="M6i", frame=True,
1393-
... land='black')
1397+
>>> fig.coast(
1398+
... region="US.HI", projection="M6i", frame=True, land="black"
1399+
... )
13941400
>>> with Session() as lib:
13951401
... wesn = lib.extract_region()
1396-
>>> print(', '.join(['{:.2f}'.format(x) for x in wesn]))
1402+
>>> print(", ".join(["{:.2f}".format(x) for x in wesn]))
13971403
-164.71, -154.81, 18.91, 23.58
13981404
13991405
The country codes can have an extra argument that rounds the region a
14001406
multiple of the argument (for example, ``'US.HI+r5'`` will round the
14011407
region to multiples of 5):
14021408
14031409
>>> fig = pygmt.Figure()
1404-
>>> fig.coast(region='US.HI+r5', projection="M6i", frame=True,
1405-
... land='black')
1410+
>>> fig.coast(
1411+
... region="US.HI+r5", projection="M6i", frame=True, land="black"
1412+
... )
14061413
>>> with Session() as lib:
14071414
... wesn = lib.extract_region()
1408-
>>> print(', '.join(['{:.2f}'.format(x) for x in wesn]))
1415+
>>> print(", ".join(["{:.2f}".format(x) for x in wesn]))
14091416
-165.00, -150.00, 15.00, 25.00
14101417
14111418
"""

pygmt/figure.py

+5-5
Original file line numberDiff line numberDiff line change
@@ -43,21 +43,21 @@ class Figure(BasePlotting):
4343
--------
4444
4545
>>> fig = Figure()
46-
>>> fig.basemap(region=[0, 360, -90, 90], projection='W7i', frame=True)
46+
>>> fig.basemap(region=[0, 360, -90, 90], projection="W7i", frame=True)
4747
>>> fig.savefig("my-figure.png")
4848
>>> # Make sure the figure file is generated and clean it up
4949
>>> import os
50-
>>> os.path.exists('my-figure.png')
50+
>>> os.path.exists("my-figure.png")
5151
True
52-
>>> os.remove('my-figure.png')
52+
>>> os.remove("my-figure.png")
5353
5454
The plot region can be specified through ISO country codes (for example,
5555
``'JP'`` for Japan):
5656
5757
>>> fig = Figure()
58-
>>> fig.basemap(region='JP', projection="M3i", frame=True)
58+
>>> fig.basemap(region="JP", projection="M3i", frame=True)
5959
>>> # The fig.region attribute shows the WESN bounding box for the figure
60-
>>> print(', '.join('{:.2f}'.format(i) for i in fig.region))
60+
>>> print(", ".join("{:.2f}".format(i) for i in fig.region))
6161
122.94, 145.82, 20.53, 45.52
6262
6363
"""

pygmt/helpers/decorators.py

+20-16
Original file line numberDiff line numberDiff line change
@@ -154,7 +154,7 @@ def fmt_docstring(module_func):
154154
--------
155155
156156
>>> @fmt_docstring
157-
... @use_alias(R='region', J='projection')
157+
... @use_alias(R="region", J="projection")
158158
... def gmtinfo(**kwargs):
159159
... '''
160160
... My nice module.
@@ -230,19 +230,19 @@ def use_alias(**aliases):
230230
Examples
231231
--------
232232
233-
>>> @use_alias(R='region', J='projection')
233+
>>> @use_alias(R="region", J="projection")
234234
... def my_module(**kwargs):
235-
... print('R =', kwargs['R'], 'J =', kwargs['J'])
236-
>>> my_module(R='bla', J='meh')
235+
... print("R =", kwargs["R"], "J =", kwargs["J"])
236+
>>> my_module(R="bla", J="meh")
237237
R = bla J = meh
238-
>>> my_module(region='bla', J='meh')
238+
>>> my_module(region="bla", J="meh")
239239
R = bla J = meh
240-
>>> my_module(R='bla', projection='meh')
240+
>>> my_module(R="bla", projection="meh")
241241
R = bla J = meh
242-
>>> my_module(region='bla', projection='meh')
242+
>>> my_module(region="bla", projection="meh")
243243
R = bla J = meh
244244
>>> my_module(
245-
... region='bla', projection='meh', J="bla"
245+
... region="bla", projection="meh", J="bla"
246246
... ) # doctest: +NORMALIZE_WHITESPACE
247247
Traceback (most recent call last):
248248
...
@@ -309,21 +309,25 @@ def kwargs_to_strings(convert_bools=True, **conversions):
309309
--------
310310
311311
>>> @kwargs_to_strings(
312-
... R='sequence', i='sequence_comma', files='sequence_space'
312+
... R="sequence", i="sequence_comma", files="sequence_space"
313313
... )
314314
... def module(*args, **kwargs):
315315
... "A module that prints the arguments it received"
316-
... print('{', end='')
317-
... print(', '.join(
318-
... "'{}': {}".format(k, repr(kwargs[k])) for k in sorted(kwargs)),
319-
... end='')
320-
... print('}')
316+
... print("{", end="")
317+
... print(
318+
... ", ".join(
319+
... "'{}': {}".format(k, repr(kwargs[k]))
320+
... for k in sorted(kwargs)
321+
... ),
322+
... end="",
323+
... )
324+
... print("}")
321325
... if args:
322-
... print("args:", ' '.join('{}'.format(x) for x in args))
326+
... print("args:", " ".join("{}".format(x) for x in args))
323327
>>> module(R=[1, 2, 3, 4])
324328
{'R': '1/2/3/4'}
325329
>>> # It's already a string, do nothing
326-
>>> module(R='5/6/7/8')
330+
>>> module(R="5/6/7/8")
327331
{'R': '5/6/7/8'}
328332
>>> module(P=True)
329333
{'P': ''}

pygmt/helpers/tempfile.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ class GMTTempFile:
4545
>>> with GMTTempFile() as tmpfile:
4646
... # write data to temporary file
4747
... x = y = z = np.arange(0, 3, 1)
48-
... np.savetxt(tmpfile.name, (x, y, z), fmt='%.1f')
48+
... np.savetxt(tmpfile.name, (x, y, z), fmt="%.1f")
4949
... lines = tmpfile.read()
5050
... print(lines)
5151
... nx, ny, nz = tmpfile.loadtxt(unpack=True, dtype=float)

0 commit comments

Comments
 (0)