Skip to content

Commit

Permalink
Added Ruff linter to replace black, flake8 and isort.
Browse files Browse the repository at this point in the history
Includes Ruff autofixes:
 - 11 × D212 (multi-line-summary-first-line)
 - 1 × RET506 (superfluous-else-raise)
 - 1 × RET505 (superfluous-else-return)
 - 1 × I001 (unsorted-imports)
Added `PLR5501` to exclude list to preserve readability of TODO
block in convert method
  • Loading branch information
ukmo-ccbunney committed Nov 20, 2024
1 parent 696a76d commit 01d78a4
Show file tree
Hide file tree
Showing 4 changed files with 63 additions and 59 deletions.
26 changes: 6 additions & 20 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -64,25 +64,11 @@ repos:
types_or: [asciidoc, python, markdown, rst]
additional_dependencies: [tomli]

# TODO: To be replaced by Ruff:
- repo: https://github.com/psf/black
rev: '24.10.0'
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: "v0.7.4"
hooks:
- id: black
- id: ruff
types: [file, python]
args: [--config=./pyproject.toml, .]

# TODO: To be replaced by Ruff:
- repo: https://github.com/PyCQA/flake8
rev: '7.1.1'
hooks:
- id: flake8
types: [file, python]
args: [--config=./.flake8]

- repo: https://github.com/pycqa/isort
rev: '5.13.2'
hooks:
- id: isort
types: [file, python]
args: ["--profile", "black", "--filter-files"]
args: [--fix, --show-fixes]
- id: ruff-format
types: [file, python]
54 changes: 42 additions & 12 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -64,18 +64,6 @@ test = {file = "requirements/pypi-optional-test.txt"}
include = ["nc_time_axis*"]
where = ["src"]

[tool.black]
line-length = 79
target-version = ['py39', 'py310', 'py311']
include = '\.pyi?$'

[tool.isort]
known_first_party = "nc_time_axis"
line_length = 79
profile = "black"
skip_gitignore = "True"
verbose = "False"

[tool.pytest.ini_options]
addopts = "-ra -v --doctest-modules"
doctest_optionflags = "NORMALIZE_WHITESPACE ELLIPSIS NUMBER"
Expand All @@ -94,3 +82,45 @@ ignore = [
[tool.codespell]
ignore-words-list = "assertIn"
skip = ".git,./docs/_build"

[tool.ruff]
line-length = 88

[tool.ruff.format]
preview = false

[tool.ruff.lint]
ignore = [
# flake8-commas (COM)
# https://docs.astral.sh/ruff/rules/#flake8-commas-com
"COM812", # Trailing comma missing.
"COM819", # Trailing comma prohibited.

# flake8-implicit-str-concat (ISC)
# https://docs.astral.sh/ruff/rules/single-line-implicit-string-concatenation/
# NOTE: This rule may cause conflicts when used with "ruff format".
"ISC001", # Implicitly concatenate string literals on one line.

# TODO: exceptions that still need investigating are below.
# Might be fixable, or might become permanent (above):
"PLR5501" # collapsible-else-if; Preserve readability of TODO block in
# `convert` method
]

preview = false
select = [
"ALL",
# list specific rules to include that is skipped using numpy convention.
"D212", # Multi-line docstring summary should start at the first line
]

[tool.ruff.lint.isort]
force-sort-within-sections = true
# Change to match specific package name:
known-first-party = ["nc_time_axis"]

[tool.ruff.lint.per-file-ignores]
# All test scripts

[tool.ruff.lint.pydocstyle]
convention = "numpy"
40 changes: 14 additions & 26 deletions src/nc_time_axis/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
"""
Support for cftime axis in matplotlib.
"""Support for cftime axis in matplotlib.
"""

Expand Down Expand Up @@ -110,8 +109,8 @@
# Licensee agrees to be bound by the terms and conditions of this License
# Agreement.

import warnings
from numbers import Number
import warnings

import cftime
import matplotlib.dates as mdates
Expand All @@ -128,8 +127,7 @@


class CalendarDateTime:
"""
Container for a :py:class:`cftime.datetime` object and calendar.
"""Container for a :py:class:`cftime.datetime` object and calendar.
Parameters
----------
Expand Down Expand Up @@ -185,8 +183,7 @@ def __repr__(self):


class AutoCFTimeFormatter(mticker.Formatter):
"""
Automatic formatter for :py:class:`cftime.datetime` data.
"""Automatic formatter for :py:class:`cftime.datetime` data.
Automatically chooses a date format based on the resolution set by the
:py:class:`NetCDFDateTimeLocator`. If no resolution is set, a default
Expand Down Expand Up @@ -240,8 +237,7 @@ def __init__(self, *args, **kwargs):


class CFTimeFormatter(mticker.Formatter):
"""
A formatter for explicitly setting the format of a
"""A formatter for explicitly setting the format of a
:py:class:`cftime.datetime` axis.
Parameters
Expand All @@ -266,8 +262,7 @@ def __call__(self, x, pos=0):


class NetCDFTimeDateLocator(mticker.Locator):
"""
Determines tick locations when plotting :py:class:`cftime.datetime` data.
"""Determines tick locations when plotting :py:class:`cftime.datetime` data.
Parameters
----------
Expand Down Expand Up @@ -322,8 +317,7 @@ def __init__(self, max_n_ticks, calendar, date_unit=None, min_n_ticks=3):
self._cached_resolution = {}

def compute_resolution(self, num1, num2, date1, date2):
"""
Returns the resolution of the dates (hourly, minutely, yearly), and
"""Returns the resolution of the dates (hourly, minutely, yearly), and
an **approximate** number of those units.
"""
Expand Down Expand Up @@ -455,17 +449,15 @@ def has_year_zero(year):


class NetCDFTimeConverter(mdates.DateConverter):
"""
Converter for :py:class:`cftime.datetime` data.
"""Converter for :py:class:`cftime.datetime` data.
"""

standard_unit = "days since 2000-01-01"

@staticmethod
def axisinfo(unit, axis):
"""
Returns the :class:`~matplotlib.units.AxisInfo` for *unit*.
"""Returns the :class:`~matplotlib.units.AxisInfo` for *unit*.
*unit* is a tzinfo instance or None.
The *axis* argument is required but not used.
Expand Down Expand Up @@ -493,8 +485,7 @@ def axisinfo(unit, axis):

@classmethod
def default_units(cls, sample_point, axis):
"""
Computes some units for the given data point.
"""Computes some units for the given data point.
"""
if hasattr(sample_point, "__iter__"):
Expand All @@ -514,8 +505,7 @@ def default_units(cls, sample_point, axis):
"Expecting cftimes with an extra " '"calendar" attribute.'
)
raise ValueError(msg)
else:
calendar = sample_point.calendar
calendar = sample_point.calendar
date_type = type(sample_point)
if calendar == "":
raise ValueError(
Expand All @@ -525,8 +515,7 @@ def default_units(cls, sample_point, axis):

@classmethod
def convert(cls, value, unit, axis):
"""
Converts value, if it is not already a number or sequence of numbers,
"""Converts value, if it is not already a number or sequence of numbers,
with :py:func:`cftime.date2num`.
"""
Expand All @@ -546,7 +535,7 @@ def convert(cls, value, unit, axis):
if is_numlike(value):
return value
# Not an array but a list of non-numerical types (thus assuming datetime types)
elif isinstance(value, (list, tuple)):
if isinstance(value, (list, tuple)):
first_value = value[0]
else:
# Neither numerical, list or ndarray : must be a datetime scalar.
Expand Down Expand Up @@ -584,8 +573,7 @@ def convert(cls, value, unit, axis):


def is_numlike(x):
"""
The Matplotlib datalim, autoscaling, locators etc work with scalars which
"""The Matplotlib datalim, autoscaling, locators etc work with scalars which
are the units converted to floats given the current unit. The converter may
be passed these floats, or arrays of them, even when units are set.
Expand Down
2 changes: 1 addition & 1 deletion src/nc_time_axis/tests/unit/test_AutoCFTimeFormatter.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
"""Unit tests for the `nc_time_axis.AutoCFTimeFormatter` class."""

import unittest
import unittest.mock as mock
from unittest import mock

import pytest

Expand Down

0 comments on commit 01d78a4

Please sign in to comment.