Skip to content

Commit

Permalink
Ruff violation icn001 fix (astropy#15899)
Browse files Browse the repository at this point in the history
* initial ICN001 fix and removed it from ignore list

* changed numpy import alias in setup_packages and used minversion in test_masking

* moved numpy import to the top in units, removed leftover matplotlib import in mpl_normalize and updated docs
  • Loading branch information
Shaheer-Ahmd authored Jan 22, 2024
1 parent 1d9088a commit aeb53d5
Show file tree
Hide file tree
Showing 25 changed files with 65 additions and 70 deletions.
4 changes: 2 additions & 2 deletions .pyinstaller/run_astropy_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import sys

import erfa # noqa: F401
import matplotlib
import matplotlib as mpl
import pytest

import astropy # noqa: F401
Expand Down Expand Up @@ -86,7 +86,7 @@

# matplotlib hook in pyinstaller 5.0 and later no longer collects every backend, see
# https://github.com/pyinstaller/pyinstaller/issues/6760
matplotlib.use("svg")
mpl.use("svg")

# We skip a few tests, which are generally ones that rely on explicitly
# checking the name of the current module (which ends up starting with
Expand Down
3 changes: 0 additions & 3 deletions .ruff.toml
Original file line number Diff line number Diff line change
Expand Up @@ -83,9 +83,6 @@ lint.ignore = [
"FIX001", # Line contains FIXME. this should be fixed or at least FIXME replaced with TODO
"FIX004", # Line contains HACK. replace HACK with NOTE.

# flake8-import-conventions (ICN) : use conventional import aliases
"ICN001", # import-conventions

# pep8-naming (N)
# NOTE: some of these can/should be fixed, but this changes the API.
"N801", # invalid-class-name
Expand Down
10 changes: 5 additions & 5 deletions astropy/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@
from astropy.utils.compat.optional_deps import HAS_MATPLOTLIB

if HAS_MATPLOTLIB:
import matplotlib
import matplotlib as mpl

matplotlibrc_cache = {}

Expand Down Expand Up @@ -78,9 +78,9 @@ def pytest_configure(config):
if HAS_MATPLOTLIB:
with warnings.catch_warnings():
warnings.simplefilter("ignore")
matplotlibrc_cache.update(matplotlib.rcParams)
matplotlib.rcdefaults()
matplotlib.use("Agg")
matplotlibrc_cache.update(mpl.rcParams)
mpl.rcdefaults()
mpl.use("Agg")

# Make sure we use temporary directories for the config and cache
# so that the tests are insensitive to local configuration. Note that this
Expand Down Expand Up @@ -115,7 +115,7 @@ def pytest_unconfigure(config):
if HAS_MATPLOTLIB:
with warnings.catch_warnings():
warnings.simplefilter("ignore")
matplotlib.rcParams.update(matplotlibrc_cache)
mpl.rcParams.update(matplotlibrc_cache)
matplotlibrc_cache.clear()

if builtins._xdg_config_home_orig is None:
Expand Down
4 changes: 2 additions & 2 deletions astropy/convolution/setup_package.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import os
import sys

import numpy
from numpy import get_include as get_numpy_include
from setuptools import Extension

C_CONVOLVE_PKGDIR = os.path.relpath(os.path.dirname(__file__))
Expand All @@ -24,7 +24,7 @@ def get_extensions():
name="astropy.convolution._convolve",
define_macros=[("NPY_NO_DEPRECATED_API", "NPY_1_7_API_VERSION")],
extra_compile_args=extra_compile_args,
include_dirs=[numpy.get_include()],
include_dirs=[get_numpy_include()],
sources=sources,
)
return [_convolve_ext]
4 changes: 2 additions & 2 deletions astropy/convolution/tests/test_convolve.py
Original file line number Diff line number Diff line change
Expand Up @@ -1189,13 +1189,13 @@ def test_astropy_convolution_against_scipy():

@pytest.mark.skipif(not HAS_PANDAS, reason="Requires pandas")
def test_regression_6099():
import pandas
import pandas as pd

wave = np.array(np.linspace(5000, 5100, 10))
boxcar = 3
nonseries_result = convolve(wave, np.ones((boxcar,)) / boxcar)

wave_series = pandas.Series(wave)
wave_series = pd.Series(wave)
series_result = convolve(wave_series, np.ones((boxcar,)) / boxcar)

assert_array_almost_equal(nonseries_result, series_result)
Expand Down
26 changes: 13 additions & 13 deletions astropy/io/ascii/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
from contextlib import suppress
from io import StringIO

import numpy
import numpy as np

from astropy.table import Table
from astropy.utils.data import get_readable_fileobj
Expand Down Expand Up @@ -158,7 +158,7 @@ def _writerow(self, writerow_func, values, has_empty):
return row_string


class MaskedConstant(numpy.ma.core.MaskedConstant):
class MaskedConstant(np.ma.core.MaskedConstant):
"""A trivial extension of numpy.ma.masked.
We want to be able to put the generic term ``masked`` into a dictionary.
Expand Down Expand Up @@ -908,7 +908,7 @@ def _set_masks(self, cols):
"""READ: Replace string values in col.str_vals and set masks."""
if self.fill_values:
for col in (col for col in cols if col.fill_values):
col.mask = numpy.zeros(len(col.str_vals), dtype=bool)
col.mask = np.zeros(len(col.str_vals), dtype=bool)
for i, str_val in (
(i, x) for i, x in enumerate(col.str_vals) if x in col.fill_values
):
Expand Down Expand Up @@ -1002,7 +1002,7 @@ def convert_numpy(numpy_type):
the required type.
"""
# Infer converter type from an instance of numpy_type.
type_name = numpy.array([], dtype=numpy_type).dtype.name
type_name = np.array([], dtype=numpy_type).dtype.name
if "int" in type_name:
converter_type = IntType
elif "float" in type_name:
Expand All @@ -1020,26 +1020,26 @@ def bool_converter(vals):
for any other string values.
"""
if len(vals) == 0:
return numpy.array([], dtype=bool)
return np.array([], dtype=bool)

# Try a smaller subset first for a long array
if len(vals) > 10000:
svals = numpy.asarray(vals[:1000])
if not numpy.all(
svals = np.asarray(vals[:1000])
if not np.all(
(svals == "False") | (svals == "True") | (svals == "0") | (svals == "1")
):
raise ValueError('bool input strings must be False, True, 0, 1, or ""')
vals = numpy.asarray(vals)
vals = np.asarray(vals)

trues = (vals == "True") | (vals == "1")
falses = (vals == "False") | (vals == "0")
if not numpy.all(trues | falses):
if not np.all(trues | falses):
raise ValueError('bool input strings must be only False, True, 0, 1, or ""')

return trues

def generic_converter(vals):
return numpy.array(vals, numpy_type)
return np.array(vals, numpy_type)

converter = bool_converter if converter_type is BoolType else generic_converter

Expand Down Expand Up @@ -1068,7 +1068,7 @@ def _validate_and_copy(col, converters):
try:
# Don't allow list-like things that dtype accepts
assert type(converters) is type
converters = [numpy.dtype(converters)]
converters = [np.dtype(converters)]
except (AssertionError, TypeError):
pass

Expand Down Expand Up @@ -1183,8 +1183,8 @@ def __call__(self, cols, meta):
self._convert_vals(cols)

t_cols = [
numpy.ma.MaskedArray(x.data, mask=x.mask)
if hasattr(x, "mask") and numpy.any(x.mask)
np.ma.MaskedArray(x.data, mask=x.mask)
if hasattr(x, "mask") and np.any(x.mask)
else x.data
for x in cols
]
Expand Down
4 changes: 2 additions & 2 deletions astropy/io/ascii/setup_package.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import os

import numpy
from numpy import get_include as get_numpy_include
from setuptools import Extension

ROOT = os.path.relpath(os.path.dirname(__file__))
Expand All @@ -16,7 +16,7 @@ def get_extensions():
ascii_ext = Extension(
name="astropy.io.ascii.cparser",
define_macros=[("NPY_NO_DEPRECATED_API", "NPY_1_7_API_VERSION")],
include_dirs=[numpy.get_include()],
include_dirs=[get_numpy_include()],
sources=sources,
)
return [ascii_ext]
4 changes: 2 additions & 2 deletions astropy/io/misc/pandas/connect.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,12 +53,12 @@ def import_html_libs():
def _pandas_read(fmt, filespec, **kwargs):
"""Provide io Table connector to read table using pandas."""
try:
import pandas
import pandas as pd
except ImportError:
raise ImportError("pandas must be installed to use pandas table reader")

pandas_fmt = fmt[len(PANDAS_PREFIX) :] # chop the 'pandas.' in front
read_func = getattr(pandas, "read_" + pandas_fmt)
read_func = getattr(pd, "read_" + pandas_fmt)

# Get defaults and then override with user-supplied values
read_kwargs = PANDAS_FMTS[pandas_fmt]["read"].copy()
Expand Down
6 changes: 3 additions & 3 deletions astropy/stats/setup_package.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import os

import numpy
from numpy import get_include as get_numpy_include
from setuptools import Extension

ROOT = os.path.relpath(os.path.dirname(__file__))
Expand All @@ -15,14 +15,14 @@ def get_extensions():
name="astropy.stats._fast_sigma_clip",
define_macros=[("NPY_NO_DEPRECATED_API", "NPY_1_7_API_VERSION")],
sources=SRCFILES,
include_dirs=[numpy.get_include()],
include_dirs=[get_numpy_include()],
language="c",
)
_stats_ext = Extension(
name="astropy.stats._stats",
define_macros=[("NPY_NO_DEPRECATED_API", "NPY_1_7_API_VERSION")],
sources=[os.path.join(ROOT, "_stats.pyx")],
include_dirs=[numpy.get_include()],
include_dirs=[get_numpy_include()],
)

return [_sigma_clip_ext, _stats_ext]
4 changes: 2 additions & 2 deletions astropy/table/setup_package.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,15 @@

import os

import numpy
from numpy import get_include as get_numpy_include
from setuptools import Extension

ROOT = os.path.relpath(os.path.dirname(__file__))


def get_extensions():
sources = ["_np_utils.pyx", "_column_mixins.pyx"]
include_dirs = [numpy.get_include()]
include_dirs = [get_numpy_include()]

exts = [
Extension(
Expand Down
5 changes: 2 additions & 3 deletions astropy/table/tests/test_table.py
Original file line number Diff line number Diff line change
Expand Up @@ -2150,10 +2150,9 @@ def test_masking(self, use_nullable_int):
# No warning with the default use_nullable_int=True
d = t.to_pandas(use_nullable_int=use_nullable_int)
else:
import pandas
from packaging.version import Version
from astropy.utils.introspection import minversion

PANDAS_LT_2_0 = Version(pandas.__version__) < Version("2.0")
PANDAS_LT_2_0 = not minversion("pandas", "2.0")
if PANDAS_LT_2_0:
if PYTEST_LT_8_0:
ctx = nullcontext()
Expand Down
4 changes: 2 additions & 2 deletions astropy/time/setup_package.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

import os

import numpy
from numpy import get_include as get_numpy_include
from setuptools import Extension

C_TIME_PKGDIR = os.path.relpath(os.path.dirname(__file__))
Expand All @@ -20,7 +20,7 @@ def get_extensions():
_time_ext = Extension(
name="astropy.time._parse_times",
sources=SRC_FILES,
include_dirs=[numpy.get_include()],
include_dirs=[get_numpy_include()],
language="c",
)

Expand Down
4 changes: 2 additions & 2 deletions astropy/timeseries/periodograms/bls/setup_package.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import os

import numpy
from numpy import get_include as get_numpy_include
from setuptools import Extension

BLS_ROOT = os.path.relpath(os.path.dirname(__file__))
Expand All @@ -16,6 +16,6 @@ def get_extensions():
os.path.join(BLS_ROOT, "bls.c"),
os.path.join(BLS_ROOT, "_impl.pyx"),
],
include_dirs=[numpy.get_include()],
include_dirs=[get_numpy_include()],
)
return [ext]
4 changes: 2 additions & 2 deletions astropy/timeseries/periodograms/lombscargle/setup_package.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import os

import numpy
from numpy import get_include as get_numpy_include
from setuptools import Extension

ROOT = os.path.relpath(os.path.dirname(__file__))
Expand All @@ -13,6 +13,6 @@ def get_extensions():
"astropy.timeseries.periodograms.lombscargle.implementations.cython_impl",
define_macros=[("NPY_NO_DEPRECATED_API", "NPY_1_7_API_VERSION")],
sources=[os.path.join(ROOT, "implementations", "cython_impl.pyx")],
include_dirs=[numpy.get_include()],
include_dirs=[get_numpy_include()],
)
return [ext]
4 changes: 2 additions & 2 deletions astropy/units/astrophys.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
available in the `astropy.units` namespace.
"""

import numpy as np

from astropy.constants import si as _si

Expand All @@ -14,7 +15,6 @@
# To ensure si units of the constants can be interpreted.
set_enabled_units([si])

import numpy as _np # noqa: E402

__all__: list[str] = [] # Units are added at the end

Expand Down Expand Up @@ -156,7 +156,7 @@
)
def_unit(
["R", "Rayleigh", "rayleigh"],
(1e10 / (4 * _np.pi)) * ph * si.m**-2 * si.s**-1 * si.sr**-1,
(1e10 / (4 * np.pi)) * ph * si.m**-2 * si.s**-1 * si.sr**-1,
namespace=_ns,
prefixes=True,
doc="Rayleigh: photon flux",
Expand Down
6 changes: 3 additions & 3 deletions astropy/units/misc.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
available in the `astropy.units` namespace.
"""

import numpy as np

from astropy.constants import si as _si

Expand All @@ -14,7 +15,6 @@
# To ensure si units of the constants can be interpreted.
set_enabled_units([si])

import numpy as _np # noqa: E402

__all__: list[str] = [] # Units are added at the end

Expand All @@ -37,14 +37,14 @@

def_unit(
["cycle", "cy"],
2.0 * _np.pi * si.rad,
2.0 * np.pi * si.rad,
namespace=_ns,
prefixes=False,
doc="cycle: angular measurement, a full turn or rotation",
)
def_unit(
["spat", "sp"],
4.0 * _np.pi * si.sr,
4.0 * np.pi * si.sr,
namespace=_ns,
prefixes=False,
doc="spat: the solid angle of the sphere, 4pi sr",
Expand Down
4 changes: 2 additions & 2 deletions astropy/units/photometric.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
"""


import numpy as _numpy
import numpy as np

from astropy.constants import si as _si

Expand All @@ -31,7 +31,7 @@
)
def_unit(
["bol", "f_bol"],
_si.L_bol0 / (4 * _numpy.pi * (10.0 * astrophys.pc) ** 2),
_si.L_bol0 / (4 * np.pi * (10.0 * astrophys.pc) ** 2),
namespace=_ns,
prefixes=False,
doc=(
Expand Down
Loading

0 comments on commit aeb53d5

Please sign in to comment.