Skip to content

Commit 7051595

Browse files
authored
Remove unnecessary function and lots of linting (#132)
* IOError is now OSError in CPython, do not need to inherit from object * use PEP 585 annotations * delay annotations to allow TfsCollection hints * remove trailing whitespaces * type checking block * remove trailing whitespaces * __new__ is classmethod, should have cls as first argument * no implicit none * error messages should be defined outside raise statement * ignore unused args and kwargs in abstractmethod signature * unnecessary else * ignore for legitimate reasons, minor formatting * use PEP 585 annotations * no pass statement in exception definition * get Sequence from collections.abc * remove trailing whitespaces * use PEP 585 annotations * mutable class var should be type hinted ClassVar * Exception must not use a string literal, assign to variable first * Exception must not use a string literal, assign to variable first * reraise from previous error * also reraise from full stacktrace here * PEP 604 unions and avoid implicit optional * type checking block * let ruff know we target python 3.9 * PEP 604 unions * put annotation-only type in TYPE_CHECKING block * Use key in dict instead of key in dict.keys() * remove trailing whitespaces * Exception must not use a string literal, assign to variable first * use contextlib to suppress a specific error instead of try-except-pass * use PEP 585 annotations * PEP 604 unions and avoid implicit optional * stop caring about boolean arg * Exception must not use a string literal, assign to variable first * reraise from previous error * use PEP 585 annotations * stop caring about boolean arg * PEP 604 unions * put annotation-only type in TYPE_CHECKING block * stop caring about boolean arg * Exception must not use a string literal, assign to variable first * lets not overwrite the loop variable * use PEP 585 annotations * PEP 604 unions and avoid implicit optional * stop caring about boolean arg * remove trailing whitespaces * unnecessary else after return * no need to restate the raise error name * remove _autoset_pandas_types as we prohibit pandas <2.1 and the need for this workaround was only for pandas up to 1.3 (excluded) in which they fixed the problem. See the NOTE in the deleted function and the github comment it links to * Exception must not use a string literal, assign to variable first * use startswith with a tuple instead of several checks * use single if statement instead of nested ones * unnecessary assignment before return * elifs can be ifs since theyre after return statements * minimal formatting * Use key in dict instead of key in dict.keys() * stop caring about boolean arg * set match in pytest.raises as it was too broad * Use key in dict instead of key in dict.keys() * remove unused caplogs * set match in pytest.raises as it was too broad * should assign in access expressions * asserts should only check one thing * unused import and orders * set match in pytest.raises as it was too broad * Use key in dict instead of key in dict.keys() * remove unused caplogs * pandas as pd, numpy as np * remove unused caplogs * use dict literal * oops * help josch's eyes * bit more formatting consistency * no need for these skipifs as the condition no longer applies * again an unused import * add in progress to the changelog * noqa on the correct line again
1 parent d106b27 commit 7051595

19 files changed

+345
-325
lines changed

CHANGELOG.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,10 @@
11
# TFS-Pandas Changelog
22

3+
## IN PROGRESS - 3.9.0
4+
5+
- Fixed:
6+
- Removed a workaround function which is no longer necessary due to the higher minimum `pandas` version.
7+
38
## Version 3.8.1
49

510
- Changed:

doc/conf.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
# -*- coding: utf-8 -*-
21
#
32
# TFS-Pandas documentation build configuration file, created by
43
# sphinx-quickstart on Tue Feb 6 12:10:18 2018.
@@ -54,7 +53,7 @@ def about_package(init_posixpath: pathlib.Path) -> dict:
5453
"sphinx.ext.coverage", # Collect doc coverage stats
5554
"sphinx.ext.doctest", # Test snippets in the documentation
5655
"sphinx.ext.githubpages", # Publish HTML docs in GitHub Pages
57-
"sphinx.ext.intersphinx", # Link to other projects documentation
56+
"sphinx.ext.intersphinx", # Link to other projects' documentation
5857
"sphinx.ext.mathjax", # Render math via JavaScript
5958
"sphinx.ext.napoleon", # Support for NumPy and Google style docstrings
6059
"sphinx.ext.todo", # Support for todo items
@@ -244,4 +243,4 @@ def about_package(init_posixpath: pathlib.Path) -> dict:
244243
"matplotlib": ("https://matplotlib.org/stable/", None),
245244
"scipy": ("https://docs.scipy.org/doc/scipy/", None),
246245
"cpymad": ("https://hibtc.github.io/cpymad/", None),
247-
}
246+
}

pyproject.toml

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,3 +86,9 @@ homepage = "https://github.com/pylhc/tfs"
8686
repository = "https://github.com/pylhc/tfs"
8787
documentation = "https://pylhc.github.io/tfs/ "
8888
changelog = "https://github.com/pylhc/tfs/blob/master/CHANGELOG.md"
89+
90+
91+
[tool.ruff]
92+
93+
# Assume Python 3.9+
94+
target-version = "py39"

tests/test_collection.py

Lines changed: 16 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
import os
21
import pathlib
2+
33
import pytest
44
from pandas.testing import assert_frame_equal
55

@@ -143,8 +143,8 @@ def test_buffer_flush_nowrite(self, _input_dir_str: str, _tfs_x: TfsDataFrame, _
143143
assert_frame_equal(tfs_y, read_tfs(c.get_path("nofile_y"), index=c.INDEX))
144144

145145
c.allow_write = False
146-
with pytest.raises(IOError):
147-
c.flush()
146+
with pytest.raises(OSError, match="Cannot flush TfsCollection"):
147+
c.flush() # because allow_write is set to False
148148

149149
tfs_x_after_flush = read_tfs(c.get_path("file_x"), index=c.INDEX)
150150
tfs_y_after_flush = read_tfs(c.get_path("nofile_y"), index=c.INDEX)
@@ -156,7 +156,7 @@ class TestFilenames:
156156

157157
def test_tfscollection_getfilename_not_implemented(self):
158158
with pytest.raises(NotImplementedError):
159-
TfsCollection._get_filename("doesnt matter")
159+
TfsCollection._get_filename("doesnt matter") # noqa: SLF001
160160

161161
def test_get_filename(self, _input_dir_pathlib: pathlib.Path):
162162
c = CollectionTest(_input_dir_pathlib, allow_write=False)
@@ -186,13 +186,13 @@ def test_filenames(self, _input_dir_pathlib: pathlib.Path):
186186
assert c.filenames()["file_x"] == "file_x.tfs"
187187
assert c.filenames()["nofile_y"] == "nofile_y.tfs"
188188

189-
assert all(f in c.filenames().keys() for f in exist_properties)
190-
assert all(f in c.filenames().keys() for f in not_exist_properties)
189+
assert all(f in c.filenames() for f in exist_properties)
190+
assert all(f in c.filenames() for f in not_exist_properties)
191191
assert all(f in c.filenames().values() for f in exist_files)
192192
assert all(f in c.filenames().values() for f in not_exist_files)
193193

194-
assert all(f in c.filenames(exist=True).keys() for f in exist_properties)
195-
assert all(f not in c.filenames(exist=True).keys() for f in not_exist_properties)
194+
assert all(f in c.filenames(exist=True) for f in exist_properties)
195+
assert all(f not in c.filenames(exist=True) for f in not_exist_properties)
196196
assert all(f in c.filenames(exist=True).values() for f in exist_files)
197197
assert all(f not in c.filenames(exist=True).values() for f in not_exist_files)
198198

@@ -254,10 +254,10 @@ def _test_fun(df, a, b):
254254
assert res_file[1] == 13
255255

256256
def test_buffer_clear(self, _dummy_collection):
257-
_dummy_collection._buffer["some_key"] = 5
258-
assert _dummy_collection._buffer["some_key"]
257+
_dummy_collection._buffer["some_key"] = 5 # noqa: SLF001
258+
assert _dummy_collection._buffer["some_key"] # noqa: SLF001
259259
_dummy_collection.clear()
260-
assert not _dummy_collection._buffer
260+
assert not _dummy_collection._buffer # noqa: SLF001
261261

262262
def test_no_attribute(self, _dummy_collection):
263263
with pytest.raises(AttributeError):
@@ -269,26 +269,26 @@ def _read_tfs(path):
269269
return read_tfs(path).set_index("NAME", drop=False)
270270

271271

272-
@pytest.fixture()
272+
@pytest.fixture
273273
def _tfs_x() -> TfsDataFrame:
274274
return _read_tfs(INPUT_DIR / "file_x.tfs")
275275

276276

277-
@pytest.fixture()
277+
@pytest.fixture
278278
def _tfs_y() -> TfsDataFrame:
279279
return _read_tfs(INPUT_DIR / "file_y.tfs")
280280

281281

282-
@pytest.fixture()
282+
@pytest.fixture
283283
def _input_dir_pathlib() -> pathlib.Path:
284284
return INPUT_DIR
285285

286286

287-
@pytest.fixture()
287+
@pytest.fixture
288288
def _input_dir_str() -> str:
289289
return str(INPUT_DIR)
290290

291291

292-
@pytest.fixture()
292+
@pytest.fixture
293293
def _dummy_collection() -> TfsCollection:
294294
return TfsCollection("")

tests/test_compression.py

Lines changed: 5 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22
Here we only test that reading and writing with compression keeps the data intact.
33
"""
44
import pathlib
5-
import sys
65

76
import pytest
87
from pandas._testing import assert_dict_equal
@@ -14,11 +13,6 @@
1413
CURRENT_DIR = pathlib.Path(__file__).parent
1514

1615

17-
# TODO: remove the skipif once Python 3.7 is EoL and we drop support for it
18-
@pytest.mark.skipif(
19-
sys.version_info < (3, 8),
20-
reason="Not run on Python 3.7 for format protocol incompatibility reasons",
21-
)
2216
@pytest.mark.parametrize("extension", ["gz", "bz2", "zip", "xz", "zst", "tar", "tar.gz"])
2317
def test_read_compressed_is_same_data(_tfs_filex, _tfs_compressed_filex_no_suffix, extension):
2418
"""Compare the data from a compressed file with the original one."""
@@ -33,11 +27,6 @@ def test_read_compressed_is_same_data(_tfs_filex, _tfs_compressed_filex_no_suffi
3327
assert_frame_equal(ref_df, test_df)
3428

3529

36-
# TODO: remove the skipif once Python 3.7 is EoL and we drop support for it
37-
@pytest.mark.skipif(
38-
sys.version_info < (3, 8),
39-
reason="Not run on Python 3.7 for format protocol incompatibility reasons",
40-
)
4130
@pytest.mark.parametrize("extension", ["gz", "bz2", "zip", "xz", "zst", "tar", "tar.gz"])
4231
def test_write_read_compressed(_tfs_filey, tmp_path, extension):
4332
"""Ensure that writing in compressed format preserves data."""
@@ -57,11 +46,6 @@ def test_write_read_compressed(_tfs_filey, tmp_path, extension):
5746
assert_frame_equal(ref_df, test_df)
5847

5948

60-
# TODO: remove the skipif once Python 3.7 is EoL and we drop support for it
61-
@pytest.mark.skipif(
62-
sys.version_info < (3, 8),
63-
reason="Not run on Python 3.7 for format protocol incompatibility reasons",
64-
)
6549
@pytest.mark.parametrize("extension", ["gz", "bz2", "zip", "xz", "zst", "tar", "tar.gz"])
6650
def test_read_headers_compressed(_tfs_compressed_filex_no_suffix, extension):
6751
compressed_file = _path_with_added_extension(_tfs_compressed_filex_no_suffix, extension)
@@ -70,7 +54,7 @@ def test_read_headers_compressed(_tfs_compressed_filex_no_suffix, extension):
7054
assert len(headers) > 0
7155
assert len(str(headers)) > 0
7256
assert all(
73-
key in headers.keys()
57+
key in headers
7458
for key in ["TITLE", "DPP", "Q1", "Q1RMS", "NATQ1", "NATQ1RMS", "BPMCOUNT"]
7559
)
7660

@@ -86,23 +70,23 @@ def _path_with_added_extension(path: pathlib.Path, extension: str) -> pathlib.Pa
8670
# ------ Fixtures ------ #
8771

8872

89-
@pytest.fixture()
73+
@pytest.fixture
9074
def _tfs_filex() -> pathlib.Path:
9175
return CURRENT_DIR / "inputs" / "file_x.tfs"
9276

9377

94-
@pytest.fixture()
78+
@pytest.fixture
9579
def _tfs_filey() -> pathlib.Path:
9680
return CURRENT_DIR / "inputs" / "file_y.tfs"
9781

9882

99-
@pytest.fixture()
83+
@pytest.fixture
10084
def _tfs_compressed_filex_no_suffix() -> pathlib.Path:
10185
"""Add the wanted compression suffix to this."""
10286
return CURRENT_DIR / "inputs" / "compressed" / "file_x.tfs"
10387

10488

105-
@pytest.fixture()
89+
@pytest.fixture
10690
def _tfs_compressed_filey_no_suffix() -> pathlib.Path:
10791
"""Add the wanted compression suffix to this."""
10892
return CURRENT_DIR / "inputs" / "compressed" / "file_y.tfs"

tests/test_frame.py

Lines changed: 13 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -14,29 +14,29 @@
1414

1515

1616
class TestFailures:
17-
def test_validate_raises_on_wrong_unique_behavior(self, caplog):
17+
def test_validate_raises_on_wrong_unique_behavior(self):
1818
df = TfsDataFrame(index=["A", "B", "A"], columns=["A", "B", "A"])
1919
with pytest.raises(KeyError):
2020
validate(df, "", non_unique_behavior="invalid")
2121

2222
@pytest.mark.parametrize("how", ["invalid", "not_left", "not_right"])
23-
def test_merge_headers_raises_on_invalid_how_key(self, caplog, how):
23+
def test_merge_headers_raises_on_invalid_how_key(self, how):
2424
headers_left = OrderedDict()
2525
headers_right = OrderedDict()
2626

27-
with pytest.raises(ValueError):
27+
with pytest.raises(ValueError, match="Invalid 'how' argument"):
2828
merge_headers(headers_left, headers_right, how=how)
2929

3030
def test_access_errors(self):
3131
df = TfsDataFrame(index=["A", "B", "A"], columns=["A", "B", "A"], headers={"HEADER": 10})
3232
with pytest.raises(AttributeError):
33-
df.does_not_exist
33+
_ = df.does_not_exist
3434

3535
with pytest.raises(KeyError):
36-
df["does also not exist"]
36+
_ = df["does also not exist"]
3737

3838
with pytest.raises(KeyError): # raises KeyError in pandas, TypeError in dict
39-
df[[1, 2, 3]]
39+
_ = df[[1, 2, 3]]
4040

4141

4242
class TestTfsDataFrameMerging:
@@ -79,7 +79,8 @@ def test_headers_merging_left(self, _tfs_file_x_pathlib, _tfs_file_y_pathlib, ho
7979
result = merge_headers(headers_left, headers_right, how=how)
8080

8181
assert isinstance(result, OrderedDict)
82-
assert len(result) >= len(headers_left) and len(result) >= len(headers_right) # no key disappeared
82+
assert len(result) >= len(headers_left) # no key disappeared
83+
assert len(result) >= len(headers_right) # no key disappeared
8384
for key in result: # check that we prioritized headers_left's contents
8485
if key in headers_left and key in headers_right:
8586
assert result[key] == headers_left[key]
@@ -91,7 +92,8 @@ def test_headers_merging_right(self, _tfs_file_x_pathlib, _tfs_file_y_pathlib, h
9192
result = merge_headers(headers_left, headers_right, how=how)
9293

9394
assert isinstance(result, OrderedDict)
94-
assert len(result) >= len(headers_left) and len(result) >= len(headers_right) # no key disappeared
95+
assert len(result) >= len(headers_left) # no key disappeared
96+
assert len(result) >= len(headers_right) # no key disappeared
9597
for key in result: # check that we prioritized headers_right's contents
9698
if key in headers_left and key in headers_right:
9799
assert result[key] == headers_right[key]
@@ -132,7 +134,7 @@ def test_long_headers_print(self):
132134
assert "Headers" in print_out
133135

134136
# Check that the ellipsis worked
135-
assert not all(key in print_out for key in headers.keys())
137+
assert not all(key in print_out for key in headers)
136138
assert not all(str(val) in print_out for val in headers.values())
137139
assert "..." in print_out
138140

@@ -185,11 +187,11 @@ def test_concatenating_accepts_pandas_dataframes(
185187
# ------ Fixtures ------ #
186188

187189

188-
@pytest.fixture()
190+
@pytest.fixture
189191
def _tfs_file_x_pathlib() -> pathlib.Path:
190192
return CURRENT_DIR / "inputs" / "file_x.tfs"
191193

192194

193-
@pytest.fixture()
195+
@pytest.fixture
194196
def _tfs_file_y_pathlib() -> pathlib.Path:
195197
return CURRENT_DIR / "inputs" / "file_x.tfs"

tests/test_hdf.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
1-
import sys
21

3-
import numpy as np
4-
import pytest
52
from pathlib import Path
63

7-
from tfs import TfsDataFrame, write_hdf, read_hdf
8-
from pandas.testing import assert_frame_equal
4+
import numpy as np
5+
import pytest
96
from pandas._testing import assert_dict_equal
7+
from pandas.testing import assert_frame_equal
8+
9+
from tfs import TfsDataFrame, read_hdf, write_hdf
1010

1111

1212
class TestHDF:

0 commit comments

Comments
 (0)