Skip to content

Commit 408ba2f

Browse files
authored
Merge pull request #185 from maxmind/greg/eng-1164
Misc cleanup
2 parents f5e017c + 4c9eb57 commit 408ba2f

File tree

13 files changed

+319
-242
lines changed

13 files changed

+319
-242
lines changed

docs/conf.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
#!/usr/bin/env python3
2-
# -*- coding: utf-8 -*-
32
#
43
# maxminddb documentation build configuration file, created by
54
# sphinx-quickstart on Tue Apr 9 13:34:57 2013.
@@ -12,8 +11,8 @@
1211
# All configuration values have a default; values that are commented out
1312
# serve to show the default.
1413

15-
import sys
1614
import os
15+
import sys
1716

1817
sys.path.insert(0, os.path.abspath(".."))
1918
import maxminddb

examples/benchmark.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,13 @@
11
#!/usr/bin/python
2-
# -*- coding: utf-8 -*-
32

43
import argparse
5-
import maxminddb
64
import random
75
import socket
86
import struct
97
import timeit
108

9+
import maxminddb
10+
1111
parser = argparse.ArgumentParser(description="Benchmark maxminddb.")
1212
parser.add_argument("--count", default=250000, type=int, help="number of lookups")
1313
parser.add_argument("--mode", default=0, type=int, help="reader mode to use")
@@ -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(
@@ -30,4 +30,4 @@ def lookup_ip_address():
3030
number=args.count,
3131
)
3232

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

maxminddb/__init__.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,13 +21,13 @@
2121

2222

2323
__all__ = [
24-
"InvalidDatabaseError",
2524
"MODE_AUTO",
2625
"MODE_FD",
2726
"MODE_FILE",
2827
"MODE_MEMORY",
2928
"MODE_MMAP",
3029
"MODE_MMAP_EXT",
30+
"InvalidDatabaseError",
3131
"Reader",
3232
"open_database",
3333
]
@@ -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
@@ -51,6 +51,7 @@ def open_database(
5151
a path. This mode implies MODE_MEMORY.
5252
* MODE_AUTO - tries MODE_MMAP_EXT, MODE_MMAP, MODE_FILE in that
5353
order. Default mode.
54+
5455
"""
5556
if mode not in (
5657
MODE_AUTO,
@@ -70,7 +71,7 @@ def open_database(
7071

7172
if not has_extension:
7273
raise ValueError(
73-
"MODE_MMAP_EXT requires the maxminddb.extension module to be available"
74+
"MODE_MMAP_EXT requires the maxminddb.extension module to be available",
7475
)
7576

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

maxminddb/const.py

Lines changed: 1 addition & 1 deletion
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

maxminddb/decoder.py

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
"""
88

99
import struct
10-
from typing import cast, Dict, List, Tuple, Union
10+
from typing import Dict, List, Tuple, Union, cast
1111

1212
try:
1313
# pylint: disable=unused-import
@@ -23,20 +23,21 @@
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.
3838
pointer_base -- the base number to use when decoding a pointer
3939
pointer_test -- used for internal unit testing of pointer code
40+
4041
"""
4142
self._pointer_test = pointer_test
4243
self._buffer = database_buffer
@@ -138,10 +139,11 @@ def _decode_utf8_string(self, size: int, offset: int) -> Tuple[str, int]:
138139
}
139140

140141
def decode(self, offset: int) -> Tuple[Record, int]:
141-
"""Decode a section of the data section starting at offset
142+
"""Decode a section of the data section starting at offset.
142143
143144
Arguments:
144145
offset -- the location of the data structure to decode
146+
145147
"""
146148
new_offset = offset + 1
147149
ctrl_byte = self._buffer[offset]
@@ -154,7 +156,7 @@ def decode(self, offset: int) -> Tuple[Record, int]:
154156
decoder = self._type_decoder[type_num]
155157
except KeyError as ex:
156158
raise InvalidDatabaseError(
157-
f"Unexpected type number ({type_num}) encountered"
159+
f"Unexpected type number ({type_num}) encountered",
158160
) from ex
159161

160162
(size, new_offset) = self._size_from_ctrl_byte(ctrl_byte, new_offset, type_num)
@@ -166,7 +168,7 @@ def _read_extended(self, offset: int) -> Tuple[int, int]:
166168
if type_num < 7:
167169
raise InvalidDatabaseError(
168170
"Something went horribly wrong in the decoder. An "
169-
f"extended type resolved to a type number < 8 ({type_num})"
171+
f"extended type resolved to a type number < 8 ({type_num})",
170172
)
171173
return type_num, offset + 1
172174

@@ -175,11 +177,14 @@ def _verify_size(expected: int, actual: int) -> None:
175177
if expected != actual:
176178
raise InvalidDatabaseError(
177179
"The MaxMind DB file's data section contains bad data "
178-
"(unknown data type or corrupt data)"
180+
"(unknown data type or corrupt data)",
179181
)
180182

181183
def _size_from_ctrl_byte(
182-
self, ctrl_byte: int, offset: int, type_num: int
184+
self,
185+
ctrl_byte: int,
186+
offset: int,
187+
type_num: int,
183188
) -> Tuple[int, int]:
184189
size = ctrl_byte & 0x1F
185190
if type_num == 1 or size < 29:

maxminddb/extension.pyi

Lines changed: 16 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -6,22 +6,25 @@ This module contains the C extension database reader and related classes.
66
77
"""
88

9+
# pylint: disable=E0601,E0602
910
from ipaddress import IPv4Address, IPv6Address
1011
from os import PathLike
11-
from typing import Any, AnyStr, Dict, IO, List, Optional, Tuple, Union
12+
from typing import IO, Any, AnyStr, Optional, Tuple, Union
13+
1214
from maxminddb import MODE_AUTO
1315
from maxminddb.types import Record
1416

1517
class Reader:
16-
"""
17-
A C extension implementation of a reader for the MaxMind DB format. IP
18+
"""A C extension implementation of a reader for the MaxMind DB format. IP
1819
addresses can be looked up using the ``get`` method.
1920
"""
2021

2122
closed: bool = ...
2223

2324
def __init__(
24-
self, database: Union[AnyStr, int, PathLike, IO], mode: int = MODE_AUTO
25+
self,
26+
database: Union[AnyStr, int, PathLike, IO],
27+
mode: int = MODE_AUTO,
2528
) -> None:
2629
"""Reader for the MaxMind DB file format
2730
@@ -30,6 +33,7 @@ class Reader:
3033
file, or a file descriptor in the case of MODE_FD.
3134
mode -- mode to open the database with. The only supported modes are
3235
MODE_AUTO and MODE_MMAP_EXT.
36+
3337
"""
3438

3539
def close(self) -> None:
@@ -38,25 +42,26 @@ class Reader:
3842
def get(self, ip_address: Union[str, IPv6Address, IPv4Address]) -> Optional[Record]:
3943
"""Return the record for the ip_address in the MaxMind DB
4044
41-
4245
Arguments:
4346
ip_address -- an IP address in the standard string notation
47+
4448
"""
4549

4650
def get_with_prefix_len(
47-
self, ip_address: Union[str, IPv6Address, IPv4Address]
51+
self,
52+
ip_address: Union[str, IPv6Address, IPv4Address],
4853
) -> Tuple[Optional[Record], int]:
4954
"""Return a tuple with the record and the associated prefix length
5055
51-
5256
Arguments:
5357
ip_address -- an IP address in the standard string notation
58+
5459
"""
5560

56-
def metadata(self) -> "Metadata":
61+
def metadata(self) -> Metadata:
5762
"""Return the metadata associated with the MaxMind DB file"""
5863

59-
def __enter__(self) -> "Reader": ...
64+
def __enter__(self) -> Reader: ...
6065
def __exit__(self, *args) -> None: ...
6166

6267
# pylint: disable=too-few-public-methods
@@ -85,7 +90,7 @@ class Metadata:
8590
A string identifying the database type, e.g., "GeoIP2-City".
8691
"""
8792

88-
description: Dict[str, str]
93+
description: dict[str, str]
8994
"""
9095
A map from locales to text descriptions of the database.
9196
"""
@@ -97,7 +102,7 @@ class Metadata:
97102
both IPv4 and IPv6 lookups.
98103
"""
99104

100-
languages: List[str]
105+
languages: list[str]
101106
"""
102107
A list of locale codes supported by the databse.
103108
"""

maxminddb/file.py

Lines changed: 6 additions & 6 deletions
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

0 commit comments

Comments
 (0)