Skip to content

Commit 08e370a

Browse files
MiWeissclaude
andauthored
🔧 Update linting rules and pre-commit config (py310 floor, drop setup-cfg-fmt, bump revs) (#564)
* 🔧 Update pre-commit config (py310, drop setup-cfg-fmt, bump revs) Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * 🎨 Apply updated pre-commit hooks to codebase Mechanical changes from the bumped hooks, mainly pyupgrade --py310-plus (PEP 585/604 annotations), removal of now-unused typing imports, and black 26 / isort 8 reformatting. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * 🎨 Apply pyupgrade to file missed in previous sweep The previous local pre-commit runs spuriously skipped tests/middleware_tests/test_latex_encoding.py, which made the pre-commit CI job fail on the sweep commit. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
1 parent fb2eb27 commit 08e370a

27 files changed

Lines changed: 191 additions & 288 deletions

‎.pre-commit-config.yaml‎

Lines changed: 7 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
repos:
22
- repo: https://github.com/pre-commit/pre-commit-hooks
3-
rev: v4.5.0
3+
rev: v6.0.0
44
hooks:
55
- id: trailing-whitespace
66
- id: end-of-file-fixer
@@ -25,35 +25,31 @@ repos:
2525
- id: rst-directive-colons
2626
- id: rst-inline-touching-normal
2727
- repo: https://github.com/psf/black
28-
rev: 24.2.0
28+
rev: 26.5.1
2929
hooks:
3030
- id: black
3131
args: [--safe, --quiet, --line-length=100]
3232
- repo: https://github.com/PyCQA/autoflake
33-
rev: v2.3.0
33+
rev: v2.3.3
3434
hooks:
3535
- id: autoflake
3636
args: [--in-place, --remove-unused-variable]
3737
- repo: https://github.com/pycqa/isort
38-
rev: 5.13.2
38+
rev: 8.0.1
3939
hooks:
4040
- id: isort
4141
name: isort
4242
args: ["--force-single-line", "--line-length=100", "--profile=black"]
4343
- repo: https://github.com/asottile/pyupgrade
44-
rev: v3.15.1
44+
rev: v3.21.2
4545
hooks:
4646
- id: pyupgrade
47-
args: [--py36-plus]
47+
args: [--py310-plus]
4848
- repo: https://github.com/PyCQA/flake8
49-
rev: 7.0.0
49+
rev: 7.3.0
5050
hooks:
5151
- id: flake8
5252
args: ["--ignore=E722,W503,E203", --max-line-length=110, "--per-file-ignores=*/__init__.py:F401"]
53-
- repo: https://github.com/asottile/setup-cfg-fmt
54-
rev: v2.5.0
55-
hooks:
56-
- id: setup-cfg-fmt
5753
- repo: https://github.com/HunterMcGushion/docstr_coverage
5854
rev: v2.3.2
5955
hooks:

‎bibtexparser/entrypoint.py‎

Lines changed: 21 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,8 @@
11
import codecs
22
import warnings
3-
from typing import Iterable
4-
from typing import List
3+
from collections.abc import Iterable
54
from typing import Optional
65
from typing import TextIO
7-
from typing import Tuple
8-
from typing import Union
96

107
from .library import Library
118
from .middlewares.middleware import Middleware
@@ -17,9 +14,9 @@
1714

1815

1916
def _build_parse_stack(
20-
parse_stack: Optional[Iterable[Middleware]],
21-
append_middleware: Optional[Iterable[Middleware]],
22-
) -> List[Middleware]:
17+
parse_stack: Iterable[Middleware] | None,
18+
append_middleware: Iterable[Middleware] | None,
19+
) -> list[Middleware]:
2320
if parse_stack is not None and append_middleware is not None:
2421
raise ValueError(
2522
"Provided both parse_stack and append_middleware. "
@@ -47,9 +44,9 @@ def _build_parse_stack(
4744

4845

4946
def _build_unparse_stack(
50-
unparse_stack: Optional[Iterable[Middleware]],
51-
prepend_middleware: Optional[Iterable[Middleware]],
52-
) -> List[Middleware]:
47+
unparse_stack: Iterable[Middleware] | None,
48+
prepend_middleware: Iterable[Middleware] | None,
49+
) -> list[Middleware]:
5350
if unparse_stack is not None and prepend_middleware is not None:
5451
raise ValueError(
5552
"Provided both unparse_stack and prepend_middleware. "
@@ -77,11 +74,11 @@ def _build_unparse_stack(
7774

7875

7976
def _handle_deprecated_write_params(
80-
unparse_stack: Optional[Iterable[Middleware]],
81-
prepend_middleware: Optional[Iterable[Middleware]],
77+
unparse_stack: Iterable[Middleware] | None,
78+
prepend_middleware: Iterable[Middleware] | None,
8279
kwargs: dict,
8380
function_name: str,
84-
) -> Tuple[Optional[Iterable[Middleware]], Optional[Iterable[Middleware]]]:
81+
) -> tuple[Iterable[Middleware] | None, Iterable[Middleware] | None]:
8582
"""Handle deprecated parameter names for write functions.
8683
8784
:param unparse_stack: Current unparse_stack value
@@ -124,9 +121,9 @@ def _handle_deprecated_write_params(
124121

125122
def parse_string(
126123
bibtex_str: str,
127-
parse_stack: Optional[Iterable[Middleware]] = None,
128-
append_middleware: Optional[Iterable[Middleware]] = None,
129-
library: Optional[Library] = None,
124+
parse_stack: Iterable[Middleware] | None = None,
125+
append_middleware: Iterable[Middleware] | None = None,
126+
library: Library | None = None,
130127
) -> Library:
131128
"""Parse a BibTeX string.
132129
@@ -156,8 +153,8 @@ def parse_string(
156153

157154
def parse_file(
158155
path: str,
159-
parse_stack: Optional[Iterable[Middleware]] = None,
160-
append_middleware: Optional[Iterable[Middleware]] = None,
156+
parse_stack: Iterable[Middleware] | None = None,
157+
append_middleware: Iterable[Middleware] | None = None,
161158
encoding: str = "UTF-8",
162159
) -> Library:
163160
"""Parse a BibTeX file
@@ -188,11 +185,11 @@ def parse_file(
188185

189186

190187
def write_file(
191-
file: Union[str, TextIO],
188+
file: str | TextIO,
192189
library: Library,
193-
unparse_stack: Optional[Iterable[Middleware]] = None,
194-
prepend_middleware: Optional[Iterable[Middleware]] = None,
195-
bibtex_format: Optional[BibtexFormat] = None,
190+
unparse_stack: Iterable[Middleware] | None = None,
191+
prepend_middleware: Iterable[Middleware] | None = None,
192+
bibtex_format: BibtexFormat | None = None,
196193
encoding: str = "UTF-8",
197194
**kwargs,
198195
) -> None:
@@ -230,8 +227,8 @@ def write_file(
230227

231228
def write_string(
232229
library: Library,
233-
unparse_stack: Optional[Iterable[Middleware]] = None,
234-
prepend_middleware: Optional[Iterable[Middleware]] = None,
230+
unparse_stack: Iterable[Middleware] | None = None,
231+
prepend_middleware: Iterable[Middleware] | None = None,
235232
bibtex_format: Optional["BibtexFormat"] = None,
236233
**kwargs,
237234
) -> str:

‎bibtexparser/exceptions.py‎

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,3 @@
1-
from typing import List
2-
from typing import Optional
3-
4-
51
class ParsingException(Exception):
62
"""Generic Exception for parsing errors"""
73

@@ -25,7 +21,7 @@ def __init__(
2521
self,
2622
abort_reason: str,
2723
# Not provided if end of file is reached
28-
end_index: Optional[int] = None,
24+
end_index: int | None = None,
2925
):
3026
self.abort_reason = abort_reason
3127
self.end_index = end_index
@@ -60,6 +56,6 @@ def __init__(self, first_match, expected_match, second_match):
6056
class PartialMiddlewareException(ParsingException):
6157
"""Exception raised when a middleware could not be fully applied."""
6258

63-
def __init__(self, reasons: List[str]):
59+
def __init__(self, reasons: list[str]):
6460
reasons_string = "\n\n=====\n\n".join(reasons)
6561
super().__init__(f"Middleware could not be fully applied: {reasons_string}")

‎bibtexparser/library.py‎

Lines changed: 13 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,3 @@
1-
from typing import Dict
2-
from typing import List
3-
from typing import Union
4-
51
from .model import Block
62
from .model import DuplicateBlockKeyBlock
73
from .model import Entry
@@ -19,7 +15,7 @@ class Library:
1915

2016
def __init__(
2117
self,
22-
blocks: Union[List[Block], None] = None,
18+
blocks: list[Block] | None = None,
2319
fail_on_duplicate_key: bool = True,
2420
):
2521
self._blocks = []
@@ -28,7 +24,7 @@ def __init__(
2824
if blocks is not None:
2925
self.add(blocks, fail_on_duplicate_key=fail_on_duplicate_key)
3026

31-
def add(self, blocks: Union[List[Block], Block], fail_on_duplicate_key: bool = True):
27+
def add(self, blocks: list[Block] | Block, fail_on_duplicate_key: bool = True):
3228
"""Add blocks to library.
3329
3430
The adding is key-safe, i.e., it is made sure that no duplicate keys are added
@@ -64,7 +60,7 @@ def add(self, blocks: Union[List[Block], Block], fail_on_duplicate_key: bool = T
6460
block = self._add_to_dicts(block)
6561
self._blocks.append(block)
6662

67-
def _find_duplicate_keys(self, blocks: List[Block]) -> List[str]:
63+
def _find_duplicate_keys(self, blocks: list[Block]) -> list[str]:
6864
"""Keys of blocks that would become duplicates when added to the library."""
6965
duplicate_keys = []
7066
seen_entry_keys = set(self._entries_by_key)
@@ -91,7 +87,7 @@ def _block_index(self, block: Block) -> int:
9187
# No identity match; fall back to equality (raises ValueError if not found).
9288
return self._blocks.index(block)
9389

94-
def remove(self, blocks: Union[List[Block], Block]):
90+
def remove(self, blocks: list[Block] | Block):
9591
"""Remove blocks from library.
9692
9793
If equal duplicate blocks exist in the library, the exact (identical)
@@ -143,9 +139,7 @@ def replace(self, old_block: Block, new_block: Block, fail_on_duplicate_key: boo
143139
raise ValueError("Duplicate key found.")
144140

145141
@staticmethod
146-
def _cast_to_duplicate(
147-
prev_block_with_same_key: Union[Entry, String], duplicate: Union[Entry, String]
148-
):
142+
def _cast_to_duplicate(prev_block_with_same_key: Entry | String, duplicate: Entry | String):
149143
if not (
150144
isinstance(prev_block_with_same_key, type(duplicate))
151145
or isinstance(duplicate, type(prev_block_with_same_key))
@@ -196,44 +190,44 @@ def _add_to_dicts(self, block):
196190
return block
197191

198192
@property
199-
def blocks(self) -> List[Block]:
193+
def blocks(self) -> list[Block]:
200194
"""All blocks in the library, preserving order of insertion."""
201195
return self._blocks
202196

203197
@property
204-
def failed_blocks(self) -> List[ParsingFailedBlock]:
198+
def failed_blocks(self) -> list[ParsingFailedBlock]:
205199
"""All blocks that could not be parsed, preserving order of insertion."""
206200
return [b for b in self._blocks if isinstance(b, ParsingFailedBlock)]
207201

208202
@property
209-
def strings(self) -> List[String]:
203+
def strings(self) -> list[String]:
210204
"""All @string blocks in the library, preserving order of insertion."""
211205
return list(self._strings_by_key.values())
212206

213207
@property
214-
def strings_dict(self) -> Dict[str, String]:
208+
def strings_dict(self) -> dict[str, String]:
215209
"""Dict representation of all @string blocks in the library."""
216210
return self._strings_by_key.copy()
217211

218212
@property
219-
def entries(self) -> List[Entry]:
213+
def entries(self) -> list[Entry]:
220214
"""All entry (@article, ...) blocks in the library, preserving order of insertion."""
221215
# Note: Taking this from the entries dict would be faster, but does not preserve order
222216
# e.g. in cases where `replace` has been called.
223217
return [b for b in self._blocks if isinstance(b, Entry)]
224218

225219
@property
226-
def entries_dict(self) -> Dict[str, Entry]:
220+
def entries_dict(self) -> dict[str, Entry]:
227221
"""Dict representation of all entry blocks in the library."""
228222
return self._entries_by_key.copy()
229223

230224
@property
231-
def preambles(self) -> List[Preamble]:
225+
def preambles(self) -> list[Preamble]:
232226
"""All @preamble blocks in the library, preserving order of insertion."""
233227
return [block for block in self._blocks if isinstance(block, Preamble)]
234228

235229
@property
236-
def comments(self) -> List[Union[ExplicitComment, ImplicitComment]]:
230+
def comments(self) -> list[ExplicitComment | ImplicitComment]:
237231
"""All comment blocks in the library, preserving order of insertion."""
238232
return [
239233
block for block in self._blocks if isinstance(block, (ExplicitComment, ImplicitComment))

‎bibtexparser/middlewares/enclosing.py‎

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,3 @@
1-
from typing import Optional
2-
from typing import Tuple
3-
from typing import Union
4-
51
from bibtexparser.library import Library
62
from bibtexparser.model import Entry
73
from bibtexparser.model import Field
@@ -53,7 +49,7 @@ def metadata_key(cls) -> str:
5349
return REMOVED_ENCLOSING_KEY
5450

5551
@staticmethod
56-
def _strip_enclosing(value: str) -> Tuple[str, Union[str, None]]:
52+
def _strip_enclosing(value: str) -> tuple[str, str | None]:
5753
value = value.strip()
5854
if value.startswith("{") and value.endswith("}"):
5955
return value[1:-1], "{"
@@ -144,9 +140,9 @@ def metadata_key(cls) -> str:
144140
def _enclose(
145141
self,
146142
value: str,
147-
metadata_enclosing: Optional[str],
143+
metadata_enclosing: str | None,
148144
apply_int_rule: bool,
149-
demanded_enclosing: Optional[str] = None,
145+
demanded_enclosing: str | None = None,
150146
) -> str:
151147
enclosing = self._default_enclosing
152148
if demanded_enclosing is not None:

‎bibtexparser/middlewares/fieldkeys.py‎

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,4 @@
11
import logging
2-
from typing import Dict
3-
from typing import List
4-
from typing import Set
52

63
from bibtexparser.library import Library
74
from bibtexparser.model import Entry
@@ -29,8 +26,8 @@ def __init__(self, allow_inplace_modification: bool = True):
2926

3027
# docstr-coverage: inherited
3128
def transform_entry(self, entry: Entry, library: "Library") -> Entry:
32-
seen_normalized_keys: Set[str] = set()
33-
new_fields_dict: Dict[str, Field] = {}
29+
seen_normalized_keys: set[str] = set()
30+
new_fields_dict: dict[str, Field] = {}
3431
for field in entry.fields:
3532
normalized_key: str = field.key.lower()
3633
# if the normalized key is already present, apply "last one wins"
@@ -48,7 +45,7 @@ def transform_entry(self, entry: Entry, library: "Library") -> Entry:
4845
field.key = normalized_key
4946
new_fields_dict[normalized_key] = field
5047

51-
new_fields: List[Field] = list(new_fields_dict.values())
48+
new_fields: list[Field] = list(new_fields_dict.values())
5249
entry.fields = new_fields
5350

5451
return entry

0 commit comments

Comments
 (0)