Skip to content

Commit

Permalink
Merge pull request #558 from larrybradley/add-linters
Browse files Browse the repository at this point in the history
Misc fixes caught by linters
  • Loading branch information
larrybradley authored Aug 9, 2024
2 parents 2fa96d3 + 44c628c commit 254ecf2
Show file tree
Hide file tree
Showing 39 changed files with 255 additions and 175 deletions.
14 changes: 14 additions & 0 deletions .github/dependabot.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# Keep dependencies updated with Dependabot version updates
# https://docs.github.com/en/code-security/dependabot/dependabot-version-updates
# https://docs.github.com/en/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file
version: 2
updates:
# Maintain dependencies for GitHub Actions
- package-ecosystem: "github-actions"
directory: ".github/workflows/"
schedule:
interval: "weekly"
groups:
actions:
patterns:
- "*"
6 changes: 3 additions & 3 deletions .github/workflows/codeql.yml
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ jobs:

# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
uses: github/codeql-action/init@v2
uses: github/codeql-action/init@v3
with:
languages: ${{ matrix.language }}
# If you wish to specify custom queries, you can do so here or in a config file.
Expand All @@ -61,7 +61,7 @@ jobs:
# Autobuild attempts to build any compiled languages (C/C++, C#, Go, or Java).
# If this step fails, then you should remove it and run the build manually (see below)
- name: Autobuild
uses: github/codeql-action/autobuild@v2
uses: github/codeql-action/autobuild@v3

# ℹ️ Command-line programs to run using the OS shell.
# 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun
Expand All @@ -74,6 +74,6 @@ jobs:
# ./location_of_script_within_repo/buildscript.sh

- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v2
uses: github/codeql-action/analyze@v3
with:
category: "/language:${{matrix.language}}"
21 changes: 20 additions & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -53,13 +53,25 @@ repos:
- id: python-check-blanket-noqa
# Enforce that all noqa annotations always occur with specific codes.

- repo: https://github.com/astral-sh/ruff-pre-commit
rev: "v0.4.7"
hooks:
- id: ruff
# args: ["--fix", "--show-fixes"]
args: ["--show-fixes"]

- repo: https://github.com/asottile/pyupgrade
rev: v3.17.0
hooks:
- id: pyupgrade
args: ["--py39-plus"]
args: ["--py310-plus"]
exclude: ".*(extern.*)$"

- repo: https://github.com/scientific-python/cookie
rev: 2024.04.23
hooks:
- id: sp-repo-review

- repo: https://github.com/pycqa/isort
rev: 5.13.2
hooks:
Expand Down Expand Up @@ -90,6 +102,13 @@ repos:
additional_dependencies:
- tomli

- repo: https://github.com/PyCQA/docformatter
rev: v1.7.5
hooks:
- id: docformatter
additional_dependencies: [tomli]
args: [--in-place, --config, ./pyproject.toml]

# - repo: https://github.com/MarcoGorelli/absolufy-imports
# rev: v0.3.1
# hooks:
Expand Down
4 changes: 3 additions & 1 deletion dev/regions_parse.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,9 @@

@click.group()
def cli():
"""astropy.regions parser debugging tool."""
"""
astropy.regions parser debugging tool.
"""
pass


Expand Down
2 changes: 1 addition & 1 deletion dev/regions_pyregion_comparison.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Compare DS9 parsing of the astropy regions package to pyregion
Compare DS9 parsing of the astropy regions package to pyregion.
This scripts compares the DS9 parsing of the astropy regions package to
pyregion in two regards.
Expand Down
13 changes: 7 additions & 6 deletions docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -181,12 +181,13 @@
# Uncomment the following lines to enable the exceptions:
nitpick_filename = 'nitpick-exceptions.txt'
if os.path.isfile(nitpick_filename):
for line in open(nitpick_filename):
if line.strip() == '' or line.startswith('#'):
continue
dtype, target = line.split(None, 1)
target = target.strip()
nitpick_ignore.append((dtype, target))
with open(nitpick_filename) as fh:
for line in fh:
if line.strip() == '' or line.startswith('#'):
continue
dtype, target = line.split(None, 1)
target = target.strip()
nitpick_ignore.append((dtype, target))

# -- Options for linkcheck output ---------------------------------------------
linkcheck_retry = 5
Expand Down
60 changes: 59 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,14 @@ norecursedirs = [
astropy_header = true
doctest_plus = 'enabled'
text_file_format = 'rst'
addopts = '--color=yes --doctest-rst --arraydiff'
addopts = [
'-ra',
'--color=yes',
'--doctest-rst',
'--strict-config',
'--strict-markers',
]
log_cli_level = 'INFO'
xfail_strict = true
remote_data_strict = true
filterwarnings = [
Expand Down Expand Up @@ -151,6 +158,17 @@ exclude_lines = [
'def _ipython_key_completions_',
]

[tool.repo-review]
ignore = [
'MY', # ignore MyPy
'PC110', # ignore using black or ruff-format in pre-commit
'PC111', # ignore using blacken-docs in pre-commit
'PC140', # ignore using mypy in pre-commit
'PC180', # ignore using prettier in pre-commit
'PC901', # ignore using custom pre-commit update message
'PY005', # ignore having a tests/ folder
]

[tool.isort]
skip_glob = [
'regions/*__init__.py*',
Expand All @@ -173,3 +191,43 @@ exclude_dirs = ['*/tests/test_casa_mask.py']

[tool.bandit.assert_used]
skips = ['*_test.py', '*/test_*.py', '*/tests/helpers.py']

[tool.docformatter]
wrap-summaries = 72
pre-summary-newline = true
make-summary-multi-line = true

[tool.ruff.lint]
select = ['E', 'F', 'UP', 'B', 'SIM', 'PL', 'FLY', 'NPY', 'PERF', 'INT',
'RSE', 'Q', 'N', 'W', 'D', 'I']
ignore = [
'E501',
'B028',
'B905', # revisit
'D100',
'D101',
'D102',
'D103',
'D105',
'D107',
'D200',
'D205',
'D212',
'D404',
'I001',
'PLR0912',
'PLR0913',
'PLR0915',
'PLR2004',
'PLW2901',
'Q000',
'SIM910',
'UP038',
]

[tool.ruff.lint.per-file-ignores]
'__init__.py' = ['D104', 'I']
'docs/conf.py' = ['ERA001', 'INP001', 'TRY400']

[tool.ruff.lint.pydocstyle]
convention = 'numpy'
1 change: 0 additions & 1 deletion regions/_geometry/tests/test_circular_overlap_grid.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@ def test_circular_overlap_grid(grid_size, circ_size, use_exact, subsample):
Test normalization of the overlap grid to make sure that a fully
enclosed pixel has a value of 1.0.
"""

g = circular_overlap_grid(-1.0, 1.0, -1.0, 1.0, grid_size, grid_size,
circ_size, use_exact, subsample)
assert_allclose(g.max(), 1.0)
1 change: 0 additions & 1 deletion regions/_geometry/tests/test_elliptical_overlap_grid.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@ def test_elliptical_overlap_grid(grid_size, maj_size, min_size, angle,
Test normalization of the overlap grid to make sure that a fully
enclosed pixel has a value of 1.0.
"""

g = elliptical_overlap_grid(-1.0, 1.0, -1.0, 1.0, grid_size, grid_size,
maj_size, min_size, angle, use_exact,
subsample)
Expand Down
1 change: 0 additions & 1 deletion regions/_geometry/tests/test_rectangular_overlap_grid.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@ def test_rectangular_overlap_grid(grid_size, rect_size, angle, subsample):
Test normalization of the overlap grid to make sure that a fully
enclosed pixel has a value of 1.0.
"""

g = rectangular_overlap_grid(-1.0, 1.0, -1.0, 1.0, grid_size, grid_size,
rect_size, rect_size, angle, 0, subsample)
assert_allclose(g.max(), 1.0)
8 changes: 6 additions & 2 deletions regions/_utils/examples.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,9 @@ def __init__(self, config=None):

@lazyproperty
def wcs(self):
"""World coordinate system (`~astropy.wcs.WCS`)."""
"""
World coordinate system (`~astropy.wcs.WCS`).
"""
wcs = WCS(naxis=2)
wcs.wcs.crval = self.config['crval']
wcs.wcs.crpix = self.config['crpix']
Expand All @@ -99,7 +101,9 @@ def wcs(self):

@lazyproperty
def image(self):
"""Counts image (`~astropy.io.fits.ImageHDU`)."""
"""
Return a "counts" image (`~astropy.io.fits.ImageHDU`).
"""
events = self.event_table
skycoord = SkyCoord(events['GLON'], events['GLAT'], unit='deg',
frame='galactic')
Expand Down
7 changes: 4 additions & 3 deletions regions/core/attributes.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,8 @@ def _validate(self, value):

class ScalarPixCoord(RegionAttribute):
"""
Descriptor class to check that value is a scalar `~regions.PixCoord`.
Descriptor class to check that value is a scalar
`~regions.PixCoord`.
"""

def _validate(self, value):
Expand Down Expand Up @@ -133,8 +134,8 @@ def _validate(self, value):

class PositiveScalarAngle(RegionAttribute):
"""
Descriptor class to check that value is a strictly positive
scalar angle, either an `~astropy.coordinates.Angle` or
Descriptor class to check that value is a strictly positive scalar
angle, either an `~astropy.coordinates.Angle` or
`~astropy.units.Quantity` with angular units.
"""

Expand Down
9 changes: 4 additions & 5 deletions regions/core/bounding_box.py
Original file line number Diff line number Diff line change
Expand Up @@ -209,9 +209,8 @@ def get_overlap_slices(self, shape):
def extent(self):
"""
The extent of the mask, defined as the ``(xmin, xmax, ymin,
ymax)`` bounding box from the bottom-left corner of the
lower-left pixel to the upper-right corner of the upper-right
pixel.
ymax)`` bounding box from the bottom-left corner of the lower-
left pixel to the upper-right corner of the upper-right pixel.
The upper edges here are the actual pixel positions of the
edges, i.e., they are not "exclusive" indices used for python
Expand Down Expand Up @@ -261,8 +260,8 @@ def as_artist(self, **kwargs):

def to_region(self):
"""
Return a `~regions.RectanglePixelRegion` that
represents the bounding box.
Return a `~regions.RectanglePixelRegion` that represents the
bounding box.
"""
from regions.core.pixcoord import PixCoord
from regions.shapes import RectanglePixelRegion
Expand Down
8 changes: 4 additions & 4 deletions regions/core/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -345,10 +345,10 @@ def _validate_mode(mode, subpixels):
raise ValueError(f'Invalid mask mode: {mode} (should be one '
f'of {valid_modes}')

if mode == 'subpixels':
if not isinstance(subpixels, int) or subpixels <= 0:
raise ValueError(f'Invalid subpixels value: {subpixels} '
'(should be a strictly positive integer)')
if (mode == 'subpixels'
and (not isinstance(subpixels, int) or subpixels <= 0)):
raise ValueError(f'Invalid subpixels value: {subpixels} '
'(should be a strictly positive integer)')

@abc.abstractmethod
def as_artist(self, origin=(0, 0), **kwargs):
Expand Down
14 changes: 5 additions & 9 deletions regions/core/mask.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,8 +59,8 @@ def shape(self):

def get_overlap_slices(self, shape):
"""
Get slices for the overlapping part of the region mask and a
2D array.
Get slices for the overlapping part of the region mask and a 2D
array.
Parameters
----------
Expand Down Expand Up @@ -175,10 +175,7 @@ def cutout(self, data, fill_value=0.0, copy=False):
return cutout

# cutout is always a copy for partial overlap
if ~np.isfinite(fill_value):
dtype = float
else:
dtype = data.dtype
dtype = float if ~np.isfinite(fill_value) else data.dtype
cutout = np.zeros(self.shape, dtype=dtype)
cutout[:] = fill_value
cutout[slices_small] = data[slices_large]
Expand Down Expand Up @@ -267,9 +264,8 @@ def _get_overlap_cutouts(self, shape, mask=None):
multiple associated arrays (e.g., data and error arrays). It is
used in this way by the `PixelAperture.do_photometry` method.
"""
if mask is not None:
if mask.shape != shape:
raise ValueError('mask and data must have the same shape')
if mask is not None and mask.shape != shape:
raise ValueError('mask and data must have the same shape')

slc_large, slc_small = self.get_overlap_slices(shape)
if slc_large is None: # no overlap
Expand Down
6 changes: 3 additions & 3 deletions regions/core/pixcoord.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ def __len__(self):
return len(self.x)

def __iter__(self):
for (x, y) in zip(self.x, self.y):
for (x, y) in zip(self.x, self.y, strict=True):
yield PixCoord(x=x, y=y)

def __getitem__(self, key):
Expand All @@ -129,8 +129,8 @@ def __sub__(self, other):

def __eq__(self, other):
"""
Checks whether ``other`` is `PixCoord` object and whether
their abscissa and ordinate values are equal using
Check whether ``other`` is `PixCoord` object and whether their
abscissa and ordinate values are equal using
`np.testing.assert_allclose` with its default tolerance values.
"""
if isinstance(other, self.__class__):
Expand Down
4 changes: 2 additions & 2 deletions regions/core/regions.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,8 +67,8 @@ def append(self, region):

def extend(self, regions):
"""
Extend the list of regions by appending elements from the
input regions.
Extend the list of regions by appending elements from the input
regions.
Parameters
----------
Expand Down
10 changes: 6 additions & 4 deletions regions/core/registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,15 @@


class IORegistryError(Exception):
"""Exception class for various registry errors."""
"""
Exception class for various registry errors.
"""


class RegionsRegistry:
"""
Class to hold a registry to read, write, parse, and serialize regions
in various formats.
Class to hold a registry to read, write, parse, and serialize
regions in various formats.
"""

registry = {}
Expand Down Expand Up @@ -157,7 +159,7 @@ def get_formats(cls, classobj):
if len(rows) == 1:
return Table()

cols = list(zip(*rows))
cols = list(zip(*rows, strict=True))
tbl = Table()
for col in cols:
tbl[col[0]] = col[1:]
Expand Down
Loading

0 comments on commit 254ecf2

Please sign in to comment.