11"""Pure-Python reader for the MaxMind DB file format."""
22
3+ from __future__ import annotations
4+
35try :
46 import mmap
57except ImportError :
810import contextlib
911import ipaddress
1012import struct
11- from collections .abc import Iterator
1213from ipaddress import IPv4Address , IPv6Address
13- from os import PathLike
14- from typing import IO , Any , AnyStr , Optional , Union
14+ from typing import IO , TYPE_CHECKING , Any , AnyStr
1515
1616from maxminddb .const import MODE_AUTO , MODE_FD , MODE_FILE , MODE_MEMORY , MODE_MMAP
1717from maxminddb .decoder import Decoder
1818from maxminddb .errors import InvalidDatabaseError
1919from maxminddb .file import FileBuffer
20- from maxminddb .types import Record
20+
21+ if TYPE_CHECKING :
22+ from collections .abc import Iterator
23+ from os import PathLike
24+
25+ from typing_extensions import Self
26+
27+ from maxminddb .types import Record
2128
2229_IPV4_MAX_NUM = 2 ** 32
2330
@@ -31,16 +38,16 @@ class Reader:
3138 _DATA_SECTION_SEPARATOR_SIZE = 16
3239 _METADATA_START_MARKER = b"\xab \xcd \xef MaxMind.com"
3340
34- _buffer : Union [ bytes , FileBuffer , "mmap.mmap" ]
41+ _buffer : bytes | FileBuffer | "mmap.mmap" # noqa: UP037
3542 _buffer_size : int
3643 closed : bool
3744 _decoder : Decoder
38- _metadata : " Metadata"
45+ _metadata : Metadata
3946 _ipv4_start : int
4047
4148 def __init__ (
4249 self ,
43- database : Union [ AnyStr , int , PathLike , IO ] ,
50+ database : AnyStr | int | PathLike | IO ,
4451 mode : int = MODE_AUTO ,
4552 ) -> None :
4653 """Reader for the MaxMind DB file format.
@@ -133,11 +140,11 @@ def __init__(
133140 ipv4_start = node
134141 self ._ipv4_start = ipv4_start
135142
136- def metadata (self ) -> " Metadata" :
143+ def metadata (self ) -> Metadata :
137144 """Return the metadata associated with the MaxMind DB file."""
138145 return self ._metadata
139146
140- def get (self , ip_address : Union [ str , IPv6Address , IPv4Address ] ) -> Optional [ Record ] :
147+ def get (self , ip_address : str | IPv6Address | IPv4Address ) -> Record | None :
141148 """Return the record for the ip_address in the MaxMind DB.
142149
143150 Arguments:
@@ -149,8 +156,8 @@ def get(self, ip_address: Union[str, IPv6Address, IPv4Address]) -> Optional[Reco
149156
150157 def get_with_prefix_len (
151158 self ,
152- ip_address : Union [ str , IPv6Address , IPv4Address ] ,
153- ) -> tuple [Optional [ Record ] , int ]:
159+ ip_address : str | IPv6Address | IPv4Address ,
160+ ) -> tuple [Record | None , int ]:
154161 """Return a tuple with the record and the associated prefix length.
155162
156163 Arguments:
@@ -279,7 +286,7 @@ def close(self) -> None:
279286 def __exit__ (self , * _ ) -> None : # noqa: ANN002
280287 self .close ()
281288
282- def __enter__ (self ) -> "Reader" :
289+ def __enter__ (self ) -> Self :
283290 if self .closed :
284291 msg = "Attempt to reopen a closed MaxMind DB"
285292 raise ValueError (msg )
0 commit comments