Skip to content

Commit 1968d04

Browse files
committed
Run ruff unsafe fixes
1 parent 64fb717 commit 1968d04

File tree

6 files changed

+56
-53
lines changed

6 files changed

+56
-53
lines changed

examples/benchmark.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,4 +30,3 @@ def lookup_ip_address() -> None:
3030
number=args.count,
3131
)
3232

33-
print(f"{int(args.count / elapsed):,}", "lookups per second")

maxminddb/__init__.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,8 @@ def open_database(
6363
MODE_MMAP,
6464
MODE_MMAP_EXT,
6565
):
66-
raise ValueError(f"Unsupported open mode: {mode}")
66+
msg = f"Unsupported open mode: {mode}"
67+
raise ValueError(msg)
6768

6869
has_extension = _extension and hasattr(_extension, "Reader")
6970
use_extension = has_extension if mode == MODE_AUTO else mode == MODE_MMAP_EXT
@@ -72,8 +73,9 @@ def open_database(
7273
return Reader(database, mode)
7374

7475
if not has_extension:
76+
msg = "MODE_MMAP_EXT requires the maxminddb.extension module to be available"
7577
raise ValueError(
76-
"MODE_MMAP_EXT requires the maxminddb.extension module to be available",
78+
msg,
7779
)
7880

7981
# The C type exposes the same API as the Python Reader, so for type

maxminddb/decoder.py

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -149,8 +149,9 @@ def decode(self, offset: int) -> tuple[Record, int]:
149149
try:
150150
decoder = self._type_decoder[type_num]
151151
except KeyError as ex:
152+
msg = f"Unexpected type number ({type_num}) encountered"
152153
raise InvalidDatabaseError(
153-
f"Unexpected type number ({type_num}) encountered",
154+
msg,
154155
) from ex
155156

156157
(size, new_offset) = self._size_from_ctrl_byte(ctrl_byte, new_offset, type_num)
@@ -160,18 +161,24 @@ def _read_extended(self, offset: int) -> tuple[int, int]:
160161
next_byte = self._buffer[offset]
161162
type_num = next_byte + 7
162163
if type_num < 7:
163-
raise InvalidDatabaseError(
164+
msg = (
164165
"Something went horribly wrong in the decoder. An "
165-
f"extended type resolved to a type number < 8 ({type_num})",
166+
f"extended type resolved to a type number < 8 ({type_num})"
167+
)
168+
raise InvalidDatabaseError(
169+
msg,
166170
)
167171
return type_num, offset + 1
168172

169173
@staticmethod
170174
def _verify_size(expected: int, actual: int) -> None:
171175
if expected != actual:
172-
raise InvalidDatabaseError(
176+
msg = (
173177
"The MaxMind DB file's data section contains bad data "
174-
"(unknown data type or corrupt data)",
178+
"(unknown data type or corrupt data)"
179+
)
180+
raise InvalidDatabaseError(
181+
msg,
175182
)
176183

177184
def _size_from_ctrl_byte(

maxminddb/extension.pyi

Lines changed: 17 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -1,65 +1,47 @@
1-
"""C extension database reader and related classes."""
1+
22

33
# pylint: disable=E0601,E0602
44
from ipaddress import IPv4Address, IPv6Address
55
from os import PathLike
6-
from typing import IO, Any, AnyStr, Optional, Union
6+
from typing import IO, Any, AnyStr
7+
8+
from typing_extensions import Self
79

810
from maxminddb.types import Record
911

1012
class Reader:
11-
"""A C extension implementation of a reader for the MaxMind DB format. IP
12-
addresses can be looked up using the ``get`` method.
13-
"""
13+
1414

1515
closed: bool = ...
1616

1717
def __init__(
1818
self,
19-
database: Union[AnyStr, int, PathLike, IO],
19+
database: AnyStr | int | PathLike | IO,
2020
mode: int = ...,
2121
) -> None:
22-
"""Reader for the MaxMind DB file format
23-
24-
Arguments:
25-
database -- A path to a valid MaxMind DB file such as a GeoIP2 database
26-
file, or a file descriptor in the case of MODE_FD.
27-
mode -- mode to open the database with. The only supported modes are
28-
MODE_AUTO and MODE_MMAP_EXT.
29-
30-
"""
22+
...
3123

3224
def close(self) -> None:
33-
"""Closes the MaxMind DB file and returns the resources to the system"""
25+
...
3426

35-
def get(self, ip_address: Union[str, IPv6Address, IPv4Address]) -> Optional[Record]:
36-
"""Return the record for the ip_address in the MaxMind DB
37-
38-
Arguments:
39-
ip_address -- an IP address in the standard string notation
40-
41-
"""
27+
def get(self, ip_address: str | IPv6Address | IPv4Address) -> Record | None:
28+
...
4229

4330
def get_with_prefix_len(
4431
self,
45-
ip_address: Union[str, IPv6Address, IPv4Address],
46-
) -> tuple[Optional[Record], int]:
47-
"""Return a tuple with the record and the associated prefix length
48-
49-
Arguments:
50-
ip_address -- an IP address in the standard string notation
51-
52-
"""
32+
ip_address: str | IPv6Address | IPv4Address,
33+
) -> tuple[Record | None, int]:
34+
...
5335

5436
def metadata(self) -> Metadata:
55-
"""Return the metadata associated with the MaxMind DB file"""
37+
...
5638

57-
def __enter__(self) -> Reader: ...
39+
def __enter__(self) -> Self: ...
5840
def __exit__(self, *args) -> None: ...
5941

6042
# pylint: disable=too-few-public-methods
6143
class Metadata:
62-
"""Metadata for the MaxMind DB reader"""
44+
6345

6446
binary_format_major_version: int
6547
"""
@@ -111,4 +93,4 @@ class Metadata:
11193
"""
11294

11395
def __init__(self, **kwargs: Any) -> None:
114-
"""Creates new Metadata object. kwargs are key/value pairs from spec"""
96+
...

maxminddb/file.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,8 @@ def __getitem__(self, key: Union[slice, int]):
2525
return self._read(key.stop - key.start, key.start)
2626
if isinstance(key, int):
2727
return self._read(1, key)[0]
28-
raise TypeError("Invalid argument type.")
28+
msg = "Invalid argument type."
29+
raise TypeError(msg)
2930

3031
def rfind(self, needle: bytes, start: int) -> int:
3132
"""Reverse find needle from start."""

maxminddb/reader.py

Lines changed: 21 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -77,10 +77,13 @@ def __init__(
7777
self._buffer_size = len(self._buffer) # type: ignore
7878
filename = database.name # type: ignore
7979
else:
80-
raise ValueError(
80+
msg = (
8181
f"Unsupported open mode ({mode}). Only MODE_AUTO, MODE_FILE, "
8282
"MODE_MEMORY and MODE_FD are supported by the pure Python "
83-
"Reader",
83+
"Reader"
84+
)
85+
raise ValueError(
86+
msg,
8487
)
8588

8689
metadata_start = self._buffer.rfind(
@@ -90,18 +93,22 @@ def __init__(
9093

9194
if metadata_start == -1:
9295
self.close()
93-
raise InvalidDatabaseError(
96+
msg = (
9497
f"Error opening database file ({filename}). "
95-
"Is this a valid MaxMind DB file?",
98+
"Is this a valid MaxMind DB file?"
99+
)
100+
raise InvalidDatabaseError(
101+
msg,
96102
)
97103

98104
metadata_start += len(self._METADATA_START_MARKER)
99105
metadata_decoder = Decoder(self._buffer, metadata_start)
100106
(metadata, _) = metadata_decoder.decode(metadata_start)
101107

102108
if not isinstance(metadata, dict):
109+
msg = f"Error reading metadata in database file ({filename})."
103110
raise InvalidDatabaseError(
104-
f"Error reading metadata in database file ({filename}).",
111+
msg,
105112
)
106113

107114
self._metadata = Metadata(**metadata) # pylint: disable=bad-option-value
@@ -157,12 +164,16 @@ def get_with_prefix_len(
157164
try:
158165
packed_address = bytearray(address.packed)
159166
except AttributeError as ex:
160-
raise TypeError("argument 1 must be a string or ipaddress object") from ex
167+
msg = "argument 1 must be a string or ipaddress object"
168+
raise TypeError(msg) from ex
161169

162170
if address.version == 6 and self._metadata.ip_version == 4:
163-
raise ValueError(
171+
msg = (
164172
f"Error looking up {ip_address}. You attempted to look up "
165-
"an IPv6 address in an IPv4-only database.",
173+
"an IPv6 address in an IPv4-only database."
174+
)
175+
raise ValueError(
176+
msg,
166177
)
167178

168179
(pointer, prefix_len) = self._find_address_in_tree(packed_address)
@@ -216,7 +227,8 @@ def _find_address_in_tree(self, packed: bytearray) -> tuple[int, int]:
216227
if node > node_count:
217228
return node, i
218229

219-
raise InvalidDatabaseError("Invalid node in search tree")
230+
msg = "Invalid node in search tree"
231+
raise InvalidDatabaseError(msg)
220232

221233
def _start_node(self, length: int) -> int:
222234
if self._metadata.ip_version == 6 and length == 32:

0 commit comments

Comments
 (0)