Skip to content

Commit 04260bf

Browse files
committed
Apply ruff unsafe fixes
1 parent 894b2c2 commit 04260bf

11 files changed

+94
-97
lines changed

examples/benchmark.py

+4-5
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33

44
import argparse
5+
import contextlib
56
import random
67
import socket
78
import struct
@@ -19,12 +20,10 @@
1920
reader = geoip2.database.Reader(args.file, mode=args.mode)
2021

2122

22-
def lookup_ip_address():
23+
def lookup_ip_address() -> None:
2324
ip = socket.inet_ntoa(struct.pack("!L", random.getrandbits(32)))
24-
try:
25-
record = reader.city(str(ip))
26-
except geoip2.errors.AddressNotFoundError:
27-
pass
25+
with contextlib.suppress(geoip2.errors.AddressNotFoundError):
26+
reader.city(str(ip))
2827

2928

3029
elapsed = timeit.timeit(

geoip2/_internal.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
1-
"""This package contains internal utilities"""
1+
"""This package contains internal utilities."""
22

33
# pylint: disable=too-few-public-methods
44
from abc import ABCMeta
55

66

77
class Model(metaclass=ABCMeta):
8-
"""Shared methods for MaxMind model classes"""
8+
"""Shared methods for MaxMind model classes."""
99

1010
def __eq__(self, other: object) -> bool:
1111
return isinstance(other, self.__class__) and self.to_dict() == other.to_dict()
@@ -15,7 +15,7 @@ def __ne__(self, other):
1515

1616
# pylint: disable=too-many-branches
1717
def to_dict(self):
18-
"""Returns a dict of the object suitable for serialization"""
18+
"""Returns a dict of the object suitable for serialization."""
1919
result = {}
2020
for key, value in self.__dict__.items():
2121
if key.startswith("_"):

geoip2/database.py

+7-7
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
import inspect
99
import os
1010
from collections.abc import Sequence
11-
from typing import IO, Any, AnyStr, Optional, Type, Union, cast
11+
from typing import IO, Any, AnyStr, Optional, Union, cast
1212

1313
import maxminddb
1414
from maxminddb import (
@@ -253,7 +253,7 @@ def _get(self, database_type: str, ip_address: IPAddress) -> Any:
253253

254254
def _model_for(
255255
self,
256-
model_class: Union[Type[Country], Type[Enterprise], Type[City]],
256+
model_class: Union[type[Country], type[Enterprise], type[City]],
257257
types: str,
258258
ip_address: IPAddress,
259259
) -> Union[Country, Enterprise, City]:
@@ -268,11 +268,11 @@ def _model_for(
268268
def _flat_model_for(
269269
self,
270270
model_class: Union[
271-
Type[Domain],
272-
Type[ISP],
273-
Type[ConnectionType],
274-
Type[ASN],
275-
Type[AnonymousIP],
271+
type[Domain],
272+
type[ISP],
273+
type[ConnectionType],
274+
type[ASN],
275+
type[AnonymousIP],
276276
],
277277
types: str,
278278
ip_address: IPAddress,

geoip2/errors.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ def __init__(
5353

5454
@property
5555
def network(self) -> Optional[Union[ipaddress.IPv4Network, ipaddress.IPv6Network]]:
56-
"""The network for the error"""
56+
"""The network for the error."""
5757
if self.ip_address is None or self._prefix_len is None:
5858
return None
5959
return ipaddress.ip_network(f"{self.ip_address}/{self._prefix_len}", False)

geoip2/models.py

+20-20
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
import ipaddress
1616
from abc import ABCMeta
1717
from collections.abc import Sequence
18-
from typing import Dict, List, Optional, Union
18+
from typing import Optional, Union
1919

2020
import geoip2.records
2121
from geoip2._internal import Model
@@ -81,14 +81,14 @@ def __init__(
8181
self,
8282
locales: Optional[Sequence[str]],
8383
*,
84-
continent: Optional[Dict] = None,
85-
country: Optional[Dict] = None,
84+
continent: Optional[dict] = None,
85+
country: Optional[dict] = None,
8686
ip_address: Optional[IPAddress] = None,
87-
maxmind: Optional[Dict] = None,
87+
maxmind: Optional[dict] = None,
8888
prefix_len: Optional[int] = None,
89-
registered_country: Optional[Dict] = None,
90-
represented_country: Optional[Dict] = None,
91-
traits: Optional[Dict] = None,
89+
registered_country: Optional[dict] = None,
90+
represented_country: Optional[dict] = None,
91+
traits: Optional[dict] = None,
9292
**_,
9393
) -> None:
9494
self._locales = locales
@@ -200,18 +200,18 @@ def __init__(
200200
self,
201201
locales: Optional[Sequence[str]],
202202
*,
203-
city: Optional[Dict] = None,
204-
continent: Optional[Dict] = None,
205-
country: Optional[Dict] = None,
206-
location: Optional[Dict] = None,
203+
city: Optional[dict] = None,
204+
continent: Optional[dict] = None,
205+
country: Optional[dict] = None,
206+
location: Optional[dict] = None,
207207
ip_address: Optional[IPAddress] = None,
208-
maxmind: Optional[Dict] = None,
209-
postal: Optional[Dict] = None,
208+
maxmind: Optional[dict] = None,
209+
postal: Optional[dict] = None,
210210
prefix_len: Optional[int] = None,
211-
registered_country: Optional[Dict] = None,
212-
represented_country: Optional[Dict] = None,
213-
subdivisions: Optional[List[Dict]] = None,
214-
traits: Optional[Dict] = None,
211+
registered_country: Optional[dict] = None,
212+
represented_country: Optional[dict] = None,
213+
subdivisions: Optional[list[dict]] = None,
214+
traits: Optional[dict] = None,
215215
**_,
216216
) -> None:
217217
super().__init__(
@@ -360,7 +360,7 @@ class Enterprise(City):
360360

361361

362362
class SimpleModel(Model, metaclass=ABCMeta):
363-
"""Provides basic methods for non-location models"""
363+
"""Provides basic methods for non-location models."""
364364

365365
_ip_address: IPAddress
366366
_network: Optional[Union[ipaddress.IPv4Network, ipaddress.IPv6Network]]
@@ -396,7 +396,7 @@ def __repr__(self) -> str:
396396

397397
@property
398398
def ip_address(self):
399-
"""The IP address for the record"""
399+
"""The IP address for the record."""
400400
if not isinstance(
401401
self._ip_address,
402402
(ipaddress.IPv4Address, ipaddress.IPv6Address),
@@ -406,7 +406,7 @@ def ip_address(self):
406406

407407
@property
408408
def network(self) -> Optional[Union[ipaddress.IPv4Network, ipaddress.IPv6Network]]:
409-
"""The network for the record"""
409+
"""The network for the record."""
410410
# This code is duplicated for performance reasons
411411
network = self._network
412412
if network is not None:

geoip2/records.py

+12-13
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
# pylint:disable=R0903
1313
from abc import ABCMeta
1414
from collections.abc import Sequence
15-
from typing import Dict, Optional, Type, Union
15+
from typing import Optional, Union
1616

1717
from geoip2._internal import Model
1818

@@ -28,13 +28,13 @@ def __repr__(self) -> str:
2828
class PlaceRecord(Record, metaclass=ABCMeta):
2929
"""All records with :py:attr:`names` subclass :py:class:`PlaceRecord`."""
3030

31-
names: Dict[str, str]
31+
names: dict[str, str]
3232
_locales: Sequence[str]
3333

3434
def __init__(
3535
self,
3636
locales: Optional[Sequence[str]],
37-
names: Optional[Dict[str, str]],
37+
names: Optional[dict[str, str]],
3838
) -> None:
3939
if locales is None:
4040
locales = ["en"]
@@ -98,7 +98,7 @@ def __init__(
9898
*,
9999
confidence: Optional[int] = None,
100100
geoname_id: Optional[int] = None,
101-
names: Optional[Dict[str, str]] = None,
101+
names: Optional[dict[str, str]] = None,
102102
**_,
103103
) -> None:
104104
self.confidence = confidence
@@ -152,7 +152,7 @@ def __init__(
152152
*,
153153
code: Optional[str] = None,
154154
geoname_id: Optional[int] = None,
155-
names: Optional[Dict[str, str]] = None,
155+
names: Optional[dict[str, str]] = None,
156156
**_,
157157
) -> None:
158158
self.code = code
@@ -224,7 +224,7 @@ def __init__(
224224
geoname_id: Optional[int] = None,
225225
is_in_european_union: bool = False,
226226
iso_code: Optional[str] = None,
227-
names: Optional[Dict[str, str]] = None,
227+
names: Optional[dict[str, str]] = None,
228228
**_,
229229
) -> None:
230230
self.confidence = confidence
@@ -305,7 +305,7 @@ def __init__(
305305
geoname_id: Optional[int] = None,
306306
is_in_european_union: bool = False,
307307
iso_code: Optional[str] = None,
308-
names: Optional[Dict[str, str]] = None,
308+
names: Optional[dict[str, str]] = None,
309309
# pylint:disable=redefined-builtin
310310
type: Optional[str] = None,
311311
**_,
@@ -536,7 +536,7 @@ def __init__(
536536
confidence: Optional[int] = None,
537537
geoname_id: Optional[int] = None,
538538
iso_code: Optional[str] = None,
539-
names: Optional[Dict[str, str]] = None,
539+
names: Optional[dict[str, str]] = None,
540540
**_,
541541
) -> None:
542542
self.confidence = confidence
@@ -558,13 +558,12 @@ class Subdivisions(tuple):
558558
"""
559559

560560
def __new__(
561-
cls: Type["Subdivisions"],
561+
cls: type["Subdivisions"],
562562
locales: Optional[Sequence[str]],
563563
*subdivisions,
564564
) -> "Subdivisions":
565565
subobjs = tuple(Subdivision(locales, **x) for x in subdivisions)
566-
obj = super().__new__(cls, subobjs) # type: ignore
567-
return obj
566+
return super().__new__(cls, subobjs) # type: ignore
568567

569568
def __init__(
570569
self,
@@ -925,7 +924,7 @@ def __init__(
925924

926925
@property
927926
def ip_address(self):
928-
"""The IP address for the record"""
927+
"""The IP address for the record."""
929928
if not isinstance(
930929
self._ip_address,
931930
(ipaddress.IPv4Address, ipaddress.IPv6Address),
@@ -935,7 +934,7 @@ def ip_address(self):
935934

936935
@property
937936
def network(self) -> Optional[Union[ipaddress.IPv4Network, ipaddress.IPv6Network]]:
938-
"""The network for the record"""
937+
"""The network for the record."""
939938
# This code is duplicated for performance reasons
940939
network = self._network
941940
if network is not None:

geoip2/types.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
"""Provides types used internally"""
1+
"""Provides types used internally."""
22

33
from ipaddress import IPv4Address, IPv6Address
44
from typing import Union

geoip2/webservice.py

+8-8
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@
2828
import ipaddress
2929
import json
3030
from collections.abc import Sequence
31-
from typing import Any, Dict, Optional, Type, Union, cast
31+
from typing import Any, Optional, Union, cast
3232

3333
import aiohttp
3434
import aiohttp.http
@@ -358,7 +358,7 @@ async def _session(self) -> aiohttp.ClientSession:
358358
async def _response_for(
359359
self,
360360
path: str,
361-
model_class: Union[Type[Insights], Type[City], Type[Country]],
361+
model_class: Union[type[Insights], type[City], type[Country]],
362362
ip_address: IPAddress,
363363
) -> Union[Country, City, Insights]:
364364
uri = self._uri(path, ip_address)
@@ -372,8 +372,8 @@ async def _response_for(
372372
decoded_body = self._handle_success(body, uri)
373373
return model_class(self._locales, **decoded_body)
374374

375-
async def close(self):
376-
"""Close underlying session
375+
async def close(self) -> None:
376+
"""Close underlying session.
377377
378378
This will close the session and any associated connections.
379379
"""
@@ -441,7 +441,7 @@ class Client(BaseClient):
441441
"""
442442

443443
_session: requests.Session
444-
_proxies: Optional[Dict[str, str]]
444+
_proxies: Optional[dict[str, str]]
445445

446446
def __init__( # pylint: disable=too-many-arguments,too-many-positional-arguments
447447
self,
@@ -510,7 +510,7 @@ def insights(self, ip_address: IPAddress = "me") -> Insights:
510510
def _response_for(
511511
self,
512512
path: str,
513-
model_class: Union[Type[Insights], Type[City], Type[Country]],
513+
model_class: Union[type[Insights], type[City], type[Country]],
514514
ip_address: IPAddress,
515515
) -> Union[Country, City, Insights]:
516516
uri = self._uri(path, ip_address)
@@ -523,8 +523,8 @@ def _response_for(
523523
decoded_body = self._handle_success(body, uri)
524524
return model_class(self._locales, **decoded_body)
525525

526-
def close(self):
527-
"""Close underlying session
526+
def close(self) -> None:
527+
"""Close underlying session.
528528
529529
This will close the session and any associated connections.
530530
"""

tests/database_test.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -283,5 +283,5 @@ def test_modes(self, mock_open) -> None:
283283
with geoip2.database.Reader(
284284
path,
285285
mode=geoip2.database.MODE_MMAP_EXT,
286-
) as reader:
286+
):
287287
mock_open.assert_called_once_with(path, geoip2.database.MODE_MMAP_EXT)

tests/models_test.py

+2-3
Original file line numberDiff line numberDiff line change
@@ -4,15 +4,14 @@
44
import ipaddress
55
import sys
66
import unittest
7-
from typing import Dict
87

98
sys.path.append("..")
109

1110
import geoip2.models
1211

1312

1413
class TestModels(unittest.TestCase):
15-
def setUp(self):
14+
def setUp(self) -> None:
1615
self.maxDiff = 20_000
1716

1817
def test_insights_full(self) -> None:
@@ -447,7 +446,7 @@ def test_unknown_keys(self) -> None:
447446

448447

449448
class TestNames(unittest.TestCase):
450-
raw: Dict = {
449+
raw: dict = {
451450
"continent": {
452451
"code": "NA",
453452
"geoname_id": 42,

0 commit comments

Comments
 (0)