Skip to content

Commit ef04c93

Browse files
authored
Merge pull request #99 from maxmind/greg/use-f-strings
Clean up string formatting
2 parents 42b76c4 + 69d1ba4 commit ef04c93

File tree

4 files changed

+31
-44
lines changed

4 files changed

+31
-44
lines changed

geoip2/database.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -220,13 +220,12 @@ def _get(self, database_type: str, ip_address: IPAddress) -> Any:
220220
if database_type not in self._db_type:
221221
caller = inspect.stack()[2][3]
222222
raise TypeError(
223-
"The %s method cannot be used with the "
224-
"%s database" % (caller, self._db_type)
223+
f"The {caller} method cannot be used with the {self._db_type} database",
225224
)
226225
(record, prefix_len) = self._db_reader.get_with_prefix_len(ip_address)
227226
if record is None:
228227
raise geoip2.errors.AddressNotFoundError(
229-
"The address %s is not in the database." % ip_address
228+
f"The address {ip_address} is not in the database.",
230229
)
231230
return record, prefix_len
232231

geoip2/models.py

Lines changed: 4 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -99,11 +99,8 @@ def __init__(
9999
self.raw = raw_response
100100

101101
def __repr__(self) -> str:
102-
return "{module}.{class_name}({data}, {locales})".format(
103-
module=self.__module__,
104-
class_name=self.__class__.__name__,
105-
data=self.raw,
106-
locales=self._locales,
102+
return (
103+
f"{self.__module__}.{self.__class__.__name__}({self.raw}, {self._locales})"
107104
)
108105

109106

@@ -336,12 +333,7 @@ def __init__(self, raw: Dict[str, Union[bool, str, int]]) -> None:
336333
self.ip_address = cast(str, raw.get("ip_address"))
337334

338335
def __repr__(self) -> str:
339-
# pylint: disable=no-member
340-
return "{module}.{class_name}({data})".format(
341-
module=self.__module__,
342-
class_name=self.__class__.__name__,
343-
data=str(self.raw),
344-
)
336+
return f"{self.__module__}.{self.__class__.__name__}({self.raw})"
345337

346338
@property
347339
def network(self) -> Optional[Union[ipaddress.IPv4Network, ipaddress.IPv6Network]]:
@@ -356,7 +348,7 @@ def network(self) -> Optional[Union[ipaddress.IPv4Network, ipaddress.IPv6Network
356348
prefix_len = self._prefix_len
357349
if ip_address is None or prefix_len is None:
358350
return None
359-
network = ipaddress.ip_network("{}/{}".format(ip_address, prefix_len), False)
351+
network = ipaddress.ip_network(f"{ip_address}/{prefix_len}", False)
360352
self._network = network
361353
return network
362354

geoip2/records.py

Lines changed: 9 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -20,9 +20,7 @@ class Record(SimpleEquality, metaclass=ABCMeta):
2020

2121
def __repr__(self) -> str:
2222
args = ", ".join("%s=%r" % x for x in self.__dict__.items())
23-
return "{module}.{class_name}({data})".format(
24-
module=self.__module__, class_name=self.__class__.__name__, data=args
25-
)
23+
return f"{self.__module__}.{self.__class__.__name__}({args})"
2624

2725

2826
class PlaceRecord(Record, metaclass=ABCMeta):
@@ -98,7 +96,7 @@ def __init__(
9896
confidence: Optional[int] = None,
9997
geoname_id: Optional[int] = None,
10098
names: Optional[Dict[str, str]] = None,
101-
**_
99+
**_,
102100
) -> None:
103101
self.confidence = confidence
104102
self.geoname_id = geoname_id
@@ -152,7 +150,7 @@ def __init__(
152150
code: Optional[str] = None,
153151
geoname_id: Optional[int] = None,
154152
names: Optional[Dict[str, str]] = None,
155-
**_
153+
**_,
156154
) -> None:
157155
self.code = code
158156
self.geoname_id = geoname_id
@@ -224,7 +222,7 @@ def __init__(
224222
is_in_european_union: bool = False,
225223
iso_code: Optional[str] = None,
226224
names: Optional[Dict[str, str]] = None,
227-
**_
225+
**_,
228226
) -> None:
229227
self.confidence = confidence
230228
self.geoname_id = geoname_id
@@ -307,7 +305,7 @@ def __init__(
307305
names: Optional[Dict[str, str]] = None,
308306
# pylint:disable=redefined-builtin
309307
type: Optional[str] = None,
310-
**_
308+
**_,
311309
) -> None:
312310
self.type = type
313311
super().__init__(
@@ -399,7 +397,7 @@ def __init__(
399397
metro_code: Optional[int] = None,
400398
population_density: Optional[int] = None,
401399
time_zone: Optional[str] = None,
402-
**_
400+
**_,
403401
) -> None:
404402
self.average_income = average_income
405403
self.accuracy_radius = accuracy_radius
@@ -527,7 +525,7 @@ def __init__(
527525
geoname_id: Optional[int] = None,
528526
iso_code: Optional[str] = None,
529527
names: Optional[Dict[str, str]] = None,
530-
**_
528+
**_,
531529
) -> None:
532530
self.confidence = confidence
533531
self.geoname_id = geoname_id
@@ -842,7 +840,7 @@ def __init__(
842840
static_ip_score: Optional[float] = None,
843841
user_count: Optional[int] = None,
844842
user_type: Optional[str] = None,
845-
**_
843+
**_,
846844
) -> None:
847845
self.autonomous_system_number = autonomous_system_number
848846
self.autonomous_system_organization = autonomous_system_organization
@@ -880,7 +878,7 @@ def network(self) -> Optional[Union[ipaddress.IPv4Network, ipaddress.IPv6Network
880878
prefix_len = self._prefix_len
881879
if ip_address is None or prefix_len is None:
882880
return None
883-
network = "{}/{}".format(ip_address, prefix_len)
881+
network = f"{ip_address}/{prefix_len}"
884882
network = ipaddress.ip_network(network, False)
885883
self._network = network
886884
return network # type: ignore

geoip2/webservice.py

Lines changed: 16 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -48,13 +48,12 @@
4848
from geoip2.models import City, Country, Insights
4949
from geoip2.types import IPAddress
5050

51-
_AIOHTTP_UA = "GeoIP2-Python-Client/%s %s" % (
52-
geoip2.__version__,
53-
aiohttp.http.SERVER_SOFTWARE,
51+
_AIOHTTP_UA = (
52+
f"GeoIP2-Python-Client/{geoip2.__version__} {aiohttp.http.SERVER_SOFTWARE}"
5453
)
55-
_REQUEST_UA = "GeoIP2-Python-Client/%s %s" % (
56-
geoip2.__version__,
57-
requests.utils.default_user_agent(),
54+
55+
_REQUEST_UA = (
56+
f"GeoIP2-Python-Client/{geoip2.__version__} {requests.utils.default_user_agent()}"
5857
)
5958

6059

@@ -85,7 +84,7 @@ def __init__(
8584
account_id if isinstance(account_id, bytes) else str(account_id)
8685
)
8786
self._license_key = license_key
88-
self._base_uri = "https://%s/geoip/v2.1" % host
87+
self._base_uri = f"https://{host}/geoip/v2.1"
8988
self._timeout = timeout
9089

9190
def _uri(self, path: str, ip_address: IPAddress) -> str:
@@ -99,9 +98,9 @@ def _handle_success(body: str, uri: str) -> Any:
9998
return json.loads(body)
10099
except ValueError as ex:
101100
raise GeoIP2Error(
102-
"Received a 200 response for %(uri)s"
101+
f"Received a 200 response for {uri}"
103102
" but could not decode the response as "
104-
"JSON: " % locals() + ", ".join(ex.args),
103+
"JSON: " + ", ".join(ex.args),
105104
200,
106105
uri,
107106
) from ex
@@ -120,15 +119,14 @@ def _exception_for_4xx_status(
120119
) -> GeoIP2Error:
121120
if not body:
122121
return HTTPError(
123-
"Received a %(status)i error for %(uri)s " "with no body." % locals(),
122+
f"Received a {status} error for {uri} with no body.",
124123
status,
125124
uri,
126125
body,
127126
)
128127
if content_type.find("json") == -1:
129128
return HTTPError(
130-
"Received a %i for %s with the following "
131-
"body: %s" % (status, uri, str(content_type)),
129+
f"Received a {status} for {uri} with the following body: {body}",
132130
status,
133131
uri,
134132
body,
@@ -137,8 +135,9 @@ def _exception_for_4xx_status(
137135
decoded_body = json.loads(body)
138136
except ValueError as ex:
139137
return HTTPError(
140-
"Received a %(status)i error for %(uri)s but it did"
141-
" not include the expected JSON body: " % locals() + ", ".join(ex.args),
138+
f"Received a {status} error for {uri} but it did not include "
139+
+ "the expected JSON body: "
140+
+ ", ".join(ex.args),
142141
status,
143142
uri,
144143
body,
@@ -149,7 +148,7 @@ def _exception_for_4xx_status(
149148
decoded_body.get("error"), decoded_body.get("code"), status, uri
150149
)
151150
return HTTPError(
152-
"Response contains JSON but it does not specify " "code or error keys",
151+
"Response contains JSON but it does not specify code or error keys",
153152
status,
154153
uri,
155154
body,
@@ -188,7 +187,7 @@ def _exception_for_5xx_status(
188187
status: int, uri: str, body: Optional[str]
189188
) -> HTTPError:
190189
return HTTPError(
191-
"Received a server error (%(status)i) for " "%(uri)s" % locals(),
190+
f"Received a server error ({status}) for {uri}",
192191
status,
193192
uri,
194193
body,
@@ -199,8 +198,7 @@ def _exception_for_non_200_status(
199198
status: int, uri: str, body: Optional[str]
200199
) -> HTTPError:
201200
return HTTPError(
202-
"Received a very surprising HTTP status "
203-
"(%(status)i) for %(uri)s" % locals(),
201+
f"Received a very surprising HTTP status ({status}) for {uri}",
204202
status,
205203
uri,
206204
body,

0 commit comments

Comments
 (0)