Skip to content

Commit 147f44e

Browse files
committed
Apply unsafe fixes from ruff
1 parent 62c7084 commit 147f44e

File tree

9 files changed

+49
-49
lines changed

9 files changed

+49
-49
lines changed

Diff for: examples/benchmark.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -19,9 +19,9 @@
1919
reader = maxminddb.open_database(args.file, args.mode)
2020

2121

22-
def lookup_ip_address():
22+
def lookup_ip_address() -> None:
2323
ip = socket.inet_ntoa(struct.pack("!L", random.getrandbits(32)))
24-
record = reader.get(str(ip))
24+
reader.get(str(ip))
2525

2626

2727
elapsed = timeit.timeit(

Diff for: maxminddb/__init__.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ def open_database(
3737
database: Union[AnyStr, int, os.PathLike, IO],
3838
mode: int = MODE_AUTO,
3939
) -> Reader:
40-
"""Open a MaxMind DB database
40+
"""Open a MaxMind DB database.
4141
4242
Arguments:
4343
database -- A path to a valid MaxMind DB file such as a GeoIP2 database

Diff for: maxminddb/const.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
"""Constants used in the API"""
1+
"""Constants used in the API."""
22

33
MODE_AUTO = 0
44
MODE_MMAP_EXT = 1

Diff for: maxminddb/decoder.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -23,15 +23,15 @@
2323

2424

2525
class Decoder: # pylint: disable=too-few-public-methods
26-
"""Decoder for the data section of the MaxMind DB"""
26+
"""Decoder for the data section of the MaxMind DB."""
2727

2828
def __init__(
2929
self,
3030
database_buffer: Union[FileBuffer, "mmap.mmap", bytes],
3131
pointer_base: int = 0,
3232
pointer_test: bool = False,
3333
) -> None:
34-
"""Created a Decoder for a MaxMind DB
34+
"""Created a Decoder for a MaxMind DB.
3535
3636
Arguments:
3737
database_buffer -- an mmap'd MaxMind DB file.
@@ -139,7 +139,7 @@ def _decode_utf8_string(self, size: int, offset: int) -> Tuple[str, int]:
139139
}
140140

141141
def decode(self, offset: int) -> Tuple[Record, int]:
142-
"""Decode a section of the data section starting at offset
142+
"""Decode a section of the data section starting at offset.
143143
144144
Arguments:
145145
offset -- the location of the data structure to decode

Diff for: maxminddb/extension.pyi

+3-3
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ This module contains the C extension database reader and related classes.
99
# pylint: disable=E0601,E0602
1010
from ipaddress import IPv4Address, IPv6Address
1111
from os import PathLike
12-
from typing import IO, Any, AnyStr, Dict, List, Optional, Tuple, Union
12+
from typing import IO, Any, AnyStr, Optional, Tuple, Union
1313

1414
from maxminddb.types import Record
1515

@@ -89,7 +89,7 @@ class Metadata:
8989
A string identifying the database type, e.g., "GeoIP2-City".
9090
"""
9191

92-
description: Dict[str, str]
92+
description: dict[str, str]
9393
"""
9494
A map from locales to text descriptions of the database.
9595
"""
@@ -101,7 +101,7 @@ class Metadata:
101101
both IPv4 and IPv6 lookups.
102102
"""
103103

104-
languages: List[str]
104+
languages: list[str]
105105
"""
106106
A list of locale codes supported by the databse.
107107
"""

Diff for: maxminddb/file.py

+6-6
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111

1212

1313
class FileBuffer:
14-
"""A slice-able file reader"""
14+
"""A slice-able file reader."""
1515

1616
def __init__(self, database: str) -> None:
1717
# pylint: disable=consider-using-with
@@ -28,31 +28,31 @@ def __getitem__(self, key: Union[slice, int]):
2828
raise TypeError("Invalid argument type.")
2929

3030
def rfind(self, needle: bytes, start: int) -> int:
31-
"""Reverse find needle from start"""
31+
"""Reverse find needle from start."""
3232
pos = self._read(self._size - start - 1, start).rfind(needle)
3333
if pos == -1:
3434
return pos
3535
return start + pos
3636

3737
def size(self) -> int:
38-
"""Size of file"""
38+
"""Size of file."""
3939
return self._size
4040

4141
def close(self) -> None:
42-
"""Close file"""
42+
"""Close file."""
4343
self._handle.close()
4444

4545
if hasattr(os, "pread"):
4646

4747
def _read(self, buffersize: int, offset: int) -> bytes:
48-
"""Read that uses pread"""
48+
"""Read that uses pread."""
4949
# pylint: disable=no-member
5050
return os.pread(self._handle.fileno(), buffersize, offset) # type: ignore
5151

5252
else:
5353

5454
def _read(self, buffersize: int, offset: int) -> bytes:
55-
"""Read with a lock
55+
"""Read with a lock.
5656
5757
This lock is necessary as after a fork, the different processes
5858
will share the same file table entry, even if we dup the fd, and

Diff for: maxminddb/reader.py

+16-13
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ def __init__(
4848
database: Union[AnyStr, int, PathLike, IO],
4949
mode: int = MODE_AUTO,
5050
) -> None:
51-
"""Reader for the MaxMind DB file format
51+
"""Reader for the MaxMind DB file format.
5252
5353
Arguments:
5454
database -- A path to a valid MaxMind DB file such as a GeoIP2 database
@@ -132,11 +132,11 @@ def __init__(
132132
self._ipv4_start = ipv4_start
133133

134134
def metadata(self) -> "Metadata":
135-
"""Return the metadata associated with the MaxMind DB file"""
135+
"""Return the metadata associated with the MaxMind DB file."""
136136
return self._metadata
137137

138138
def get(self, ip_address: Union[str, IPv6Address, IPv4Address]) -> Optional[Record]:
139-
"""Return the record for the ip_address in the MaxMind DB
139+
"""Return the record for the ip_address in the MaxMind DB.
140140
141141
Arguments:
142142
ip_address -- an IP address in the standard string notation
@@ -149,7 +149,7 @@ def get_with_prefix_len(
149149
self,
150150
ip_address: Union[str, IPv6Address, IPv4Address],
151151
) -> Tuple[Optional[Record], int]:
152-
"""Return a tuple with the record and the associated prefix length
152+
"""Return a tuple with the record and the associated prefix length.
153153
154154
Arguments:
155155
ip_address -- an IP address in the standard string notation
@@ -245,20 +245,22 @@ def _read_node(self, node_number: int, index: int) -> int:
245245
offset = base_offset + index * 4
246246
node_bytes = self._buffer[offset : offset + 4]
247247
else:
248-
raise InvalidDatabaseError(f"Unknown record size: {record_size}")
248+
msg = f"Unknown record size: {record_size}"
249+
raise InvalidDatabaseError(msg)
249250
return struct.unpack(b"!I", node_bytes)[0]
250251

251252
def _resolve_data_pointer(self, pointer: int) -> Record:
252253
resolved = pointer - self._metadata.node_count + self._metadata.search_tree_size
253254

254255
if resolved >= self._buffer_size:
255-
raise InvalidDatabaseError("The MaxMind DB file's search tree is corrupt")
256+
msg = "The MaxMind DB file's search tree is corrupt"
257+
raise InvalidDatabaseError(msg)
256258

257259
(data, _) = self._decoder.decode(resolved)
258260
return data
259261

260262
def close(self) -> None:
261-
"""Closes the MaxMind DB file and returns the resources to the system"""
263+
"""Closes the MaxMind DB file and returns the resources to the system."""
262264
try:
263265
self._buffer.close() # type: ignore
264266
except AttributeError:
@@ -270,13 +272,14 @@ def __exit__(self, *args) -> None:
270272

271273
def __enter__(self) -> "Reader":
272274
if self.closed:
273-
raise ValueError("Attempt to reopen a closed MaxMind DB")
275+
msg = "Attempt to reopen a closed MaxMind DB"
276+
raise ValueError(msg)
274277
return self
275278

276279

277280
# pylint: disable=too-many-instance-attributes,R0801
278281
class Metadata:
279-
"""Metadata for the MaxMind DB reader"""
282+
"""Metadata for the MaxMind DB reader."""
280283

281284
binary_format_major_version: int
282285
"""
@@ -328,7 +331,7 @@ class Metadata:
328331
"""
329332

330333
def __init__(self, **kwargs) -> None:
331-
"""Creates new Metadata object. kwargs are key/value pairs from spec"""
334+
"""Creates new Metadata object. kwargs are key/value pairs from spec."""
332335
# Although I could just update __dict__, that is less obvious and it
333336
# doesn't work well with static analysis tools and some IDEs
334337
self.node_count = kwargs["node_count"]
@@ -343,20 +346,20 @@ def __init__(self, **kwargs) -> None:
343346

344347
@property
345348
def node_byte_size(self) -> int:
346-
"""The size of a node in bytes
349+
"""The size of a node in bytes.
347350
348351
:type: int
349352
"""
350353
return self.record_size // 4
351354

352355
@property
353356
def search_tree_size(self) -> int:
354-
"""The size of the search tree
357+
"""The size of the search tree.
355358
356359
:type: int
357360
"""
358361
return self.node_count * self.node_byte_size
359362

360-
def __repr__(self):
363+
def __repr__(self) -> str:
361364
args = ", ".join(f"{k}={v!r}" for k, v in self.__dict__.items())
362365
return f"{self.__module__}.{self.__class__.__name__}({args})"

Diff for: setup.py

+10-12
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@
3737
ext_module = [
3838
Extension(
3939
"maxminddb.extension",
40-
libraries=["maxminddb"] + libraries,
40+
libraries=["maxminddb", *libraries],
4141
sources=["extension/maxminddb.c"],
4242
extra_compile_args=compile_args,
4343
),
@@ -78,20 +78,20 @@
7878

7979

8080
class BuildFailed(Exception):
81-
def __init__(self):
81+
def __init__(self) -> None:
8282
self.cause = sys.exc_info()[1]
8383

8484

8585
class ve_build_ext(build_ext):
8686
# This class allows C extension building to fail.
8787

88-
def run(self):
88+
def run(self) -> None:
8989
try:
9090
build_ext.run(self)
9191
except DistutilsPlatformError:
9292
raise BuildFailed
9393

94-
def build_extension(self, ext):
94+
def build_extension(self, ext) -> None:
9595
try:
9696
build_ext.build_extension(self, ext)
9797
except ext_errors:
@@ -120,24 +120,22 @@ def build_extension(self, ext):
120120
)
121121

122122

123-
def status_msgs(*msgs):
124-
print("*" * 75)
125-
for msg in msgs:
126-
print(msg)
127-
print("*" * 75)
123+
def status_msgs(*msgs) -> None:
124+
for _msg in msgs:
125+
pass
128126

129127

130128
def find_packages(location):
131129
packages = []
132130
for pkg in ["maxminddb"]:
133-
for _dir, subdirectories, files in os.walk(os.path.join(location, pkg)):
131+
for _dir, _subdirectories, files in os.walk(os.path.join(location, pkg)):
134132
if "__init__.py" in files:
135133
tokens = _dir.split(os.sep)[len(location.split(os.sep)) :]
136134
packages.append(".".join(tokens))
137135
return packages
138136

139137

140-
def run_setup(with_cext):
138+
def run_setup(with_cext) -> None:
141139
kwargs = {}
142140
loc_cmdclass = cmdclass.copy()
143141
if with_cext:
@@ -158,7 +156,7 @@ def run_setup(with_cext):
158156
run_setup(True)
159157
except BuildFailed as exc:
160158
if os.getenv("MAXMINDDB_REQUIRE_EXTENSION"):
161-
raise exc
159+
raise
162160
status_msgs(
163161
exc.cause,
164162
"WARNING: The C extension could not be compiled, "

Diff for: tests/reader_test.py

+7-8
Original file line numberDiff line numberDiff line change
@@ -478,9 +478,8 @@ def test_with_statement_close(self):
478478
with self.assertRaisesRegex(
479479
ValueError,
480480
"Attempt to reopen a closed MaxMind DB",
481-
):
482-
with reader:
483-
pass
481+
), reader:
482+
pass
484483

485484
def test_closed(self):
486485
reader = open_database(
@@ -523,13 +522,13 @@ def test_multiprocessing(self):
523522
def test_threading(self):
524523
self._check_concurrency(threading.Thread)
525524

526-
def _check_concurrency(self, worker_class):
525+
def _check_concurrency(self, worker_class) -> None:
527526
reader = open_database(
528527
"tests/data/test-data/GeoIP2-Domain-Test.mmdb",
529528
self.mode,
530529
)
531530

532-
def lookup(pipe):
531+
def lookup(pipe) -> None:
533532
try:
534533
for i in range(32):
535534
reader.get(self.ipf(f"65.115.240.{i}"))
@@ -554,7 +553,7 @@ def lookup(pipe):
554553

555554
self.assertEqual(count, 32, "expected number of successful lookups")
556555

557-
def _check_metadata(self, reader, ip_version, record_size):
556+
def _check_metadata(self, reader, ip_version, record_size) -> None:
558557
metadata = reader.metadata()
559558

560559
self.assertEqual(2, metadata.binary_format_major_version, "major version")
@@ -572,7 +571,7 @@ def _check_metadata(self, reader, ip_version, record_size):
572571

573572
self.assertEqual(metadata.record_size, record_size)
574573

575-
def _check_ip_v4(self, reader, file_name):
574+
def _check_ip_v4(self, reader, file_name) -> None:
576575
for i in range(6):
577576
address = "1.1.1." + str(pow(2, i))
578577
self.assertEqual(
@@ -602,7 +601,7 @@ def _check_ip_v4(self, reader, file_name):
602601
for ip in ["1.1.1.33", "255.254.253.123"]:
603602
self.assertIsNone(reader.get(self.ipf(ip)))
604603

605-
def _check_ip_v6(self, reader, file_name):
604+
def _check_ip_v6(self, reader, file_name) -> None:
606605
subnets = ["::1:ffff:ffff", "::2:0:0", "::2:0:40", "::2:0:50", "::2:0:58"]
607606

608607
for address in subnets:

0 commit comments

Comments
 (0)