Skip to content

Commit 563abb0

Browse files
committed
fix mypy errors
1 parent afc2a5b commit 563abb0

8 files changed

Lines changed: 105 additions & 59 deletions

File tree

amazon_paapi/api.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
from .helpers import arguments, requests
1212
from .helpers.generators import get_list_chunks
1313
from .helpers.items import sort_items
14+
from .models.regions import CountryCode
1415
from .sdk.api.default_api import DefaultApi
1516

1617

@@ -21,7 +22,8 @@ class AmazonApi:
2122
key (``str``): Your API key.
2223
secret (``str``): Your API secret.
2324
tag (``str``): Your affiliate tracking id, used to create the affiliate link.
24-
country (``models.Country``): Country code for your affiliate account.
25+
country (``CountryCode``): Country code for your affiliate account.
26+
Use values from ``models.Country``, e.g. ``Country.ES``.
2527
throttling (``float``, optional): Wait time in seconds between API calls. Use it
2628
to avoid reaching Amazon limits. Defaults to 1 second.
2729
@@ -35,7 +37,7 @@ def __init__(
3537
key: str,
3638
secret: str,
3739
tag: str,
38-
country: models.Country,
40+
country: CountryCode,
3941
throttling: float = 1,
4042
**kwargs,
4143
) -> None:

amazon_paapi/helpers/arguments.py

Lines changed: 24 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -7,18 +7,27 @@
77

88

99
def get_items_ids(items: Union[str, List[str]]) -> List[str]:
10-
if not isinstance(items, str) and not isinstance(items, List):
11-
msg = "Invalid items argument, it should be a string or List of strings"
12-
raise InvalidArgument(msg)
10+
"""Parse and extract ASINs from items input.
1311
12+
Args:
13+
items: Either a comma-separated string of ASINs/URLs or a list of ASINs/URLs.
14+
15+
Returns:
16+
A list of extracted ASINs.
17+
18+
Raises:
19+
InvalidArgument: If items is not a string or list.
20+
21+
"""
1422
if isinstance(items, str):
1523
items_ids = items.split(",")
16-
items_ids = [get_asin(x.strip()) for x in items_ids]
24+
return [get_asin(x.strip()) for x in items_ids]
1725

18-
else:
19-
items_ids = [get_asin(x.strip()) for x in items]
26+
if isinstance(items, list):
27+
return [get_asin(x.strip()) for x in items]
2028

21-
return items_ids
29+
msg = "Invalid items argument, it should be a string or List of strings" # type: ignore[unreachable]
30+
raise InvalidArgument(msg)
2231

2332

2433
def check_search_args(**kwargs) -> None:
@@ -46,29 +55,25 @@ def check_search_mandatory_args(**kwargs) -> None:
4655

4756

4857
def check_search_pagination_args(**kwargs) -> None:
58+
"""Validate pagination arguments for search requests."""
4959
error_message = "Args item_count and item_page should be integers between 1 and 10."
5060
pagination_args = [kwargs.get("item_count"), kwargs.get("item_page")]
51-
pagination_args = [arg for arg in pagination_args if arg]
5261

53-
if not all(isinstance(arg, int) for arg in pagination_args):
54-
raise InvalidArgument(error_message)
55-
56-
if not all(1 <= arg <= 10 for arg in pagination_args):
57-
raise InvalidArgument(error_message)
62+
for arg in pagination_args:
63+
if arg is not None and (not isinstance(arg, int) or not 1 <= arg <= 10):
64+
raise InvalidArgument(error_message)
5865

5966

6067
def check_variations_args(**kwargs) -> None:
68+
"""Validate variation arguments for get_variations requests."""
6169
error_message = (
6270
"Args variation_count and variation_page should be integers between 1 and 10."
6371
)
6472
variation_args = [kwargs.get("variation_count"), kwargs.get("variation_page")]
65-
variation_args = [arg for arg in variation_args if arg]
66-
67-
if not all(isinstance(arg, int) for arg in variation_args):
68-
raise InvalidArgument(error_message)
6973

70-
if not all(1 <= arg <= 10 for arg in variation_args):
71-
raise InvalidArgument(error_message)
74+
for arg in variation_args:
75+
if arg is not None and (not isinstance(arg, int) or not 1 <= arg <= 10):
76+
raise InvalidArgument(error_message)
7277

7378

7479
def check_browse_nodes_args(**kwargs) -> None:

amazon_paapi/helpers/items.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,11 @@
88
def sort_items(
99
items: List[models.Item], items_ids: List[str], include_unavailable: bool
1010
) -> List[models.Item]:
11-
sorted_items = []
11+
"""Sort items by the order of the provided items_ids list."""
12+
sorted_items: List[models.Item] = []
1213

1314
for asin in items_ids:
14-
matches = list(filter(lambda item, asin=asin: item.asin == asin, items))
15+
matches: List[models.Item] = [item for item in items if item.asin == asin]
1516
if matches:
1617
sorted_items.append(matches[0])
1718
elif include_unavailable:

amazon_paapi/helpers/requests.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
"""Module with helper functions for creating requests."""
22

33
import inspect
4-
from typing import List
4+
from typing import List, NoReturn, cast
55

66
from amazon_paapi.errors import (
77
AssociateValidationError,
@@ -52,7 +52,7 @@ def get_items_response(amazon_api, request: GetItemsRequest) -> List[Item]:
5252
msg = "No items have been found"
5353
raise ItemsNotFound(msg)
5454

55-
return response.items_result.items
55+
return cast(List[Item], response.items_result.items)
5656

5757

5858
def get_search_items_request(amazon_api, **kwargs) -> SearchItemsRequest:
@@ -79,7 +79,7 @@ def get_search_items_response(amazon_api, request: SearchItemsRequest) -> Search
7979
msg = "No items have been found"
8080
raise ItemsNotFound(msg)
8181

82-
return response.search_result
82+
return cast(SearchResult, response.search_result)
8383

8484

8585
def get_variations_request(amazon_api, **kwargs) -> GetVariationsRequest:
@@ -108,7 +108,7 @@ def get_variations_response(
108108
msg = "No variation items have been found"
109109
raise ItemsNotFound(msg)
110110

111-
return response.variations_result
111+
return cast(VariationsResult, response.variations_result)
112112

113113

114114
def get_browse_nodes_request(amazon_api, **kwargs) -> GetBrowseNodesRequest:
@@ -137,15 +137,15 @@ def get_browse_nodes_response(
137137
msg = "No browse nodes have been found"
138138
raise ItemsNotFound(msg)
139139

140-
return response.browse_nodes_result.browse_nodes
140+
return cast(List[BrowseNode], response.browse_nodes_result.browse_nodes)
141141

142142

143143
def _get_request_resources(resources) -> List[str]:
144144
resources = inspect.getmembers(resources, lambda a: not inspect.isroutine(a))
145145
return [x[-1] for x in resources if isinstance(x[-1], str) and x[0][0:2] != "__"]
146146

147147

148-
def _manage_response_exceptions(error) -> None:
148+
def _manage_response_exceptions(error) -> NoReturn:
149149
error_status = getattr(error, "status", None)
150150
error_body = getattr(error, "body", "") or ""
151151

amazon_paapi/models/__init__.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,18 +2,19 @@
22

33
from .browse_nodes_result import BrowseNode
44
from .item_result import Item
5-
from .regions import Country
5+
from .regions import Country, CountryCode
66
from .search_result import SearchResult
77
from .variations_result import VariationsResult
88

99
__all__ = [
1010
"Availability",
11-
"Condition",
12-
"Merchant",
13-
"SortBy",
1411
"BrowseNode",
15-
"Item",
12+
"Condition",
1613
"Country",
14+
"CountryCode",
15+
"Item",
16+
"Merchant",
1717
"SearchResult",
18+
"SortBy",
1819
"VariationsResult",
1920
]

amazon_paapi/models/regions.py

Lines changed: 57 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,62 @@
1+
from __future__ import annotations
2+
3+
from typing import Literal
4+
5+
# Type alias for valid country codes
6+
CountryCode = Literal[
7+
"AU",
8+
"BE",
9+
"BR",
10+
"CA",
11+
"FR",
12+
"DE",
13+
"IN",
14+
"IT",
15+
"JP",
16+
"MX",
17+
"NL",
18+
"PL",
19+
"SG",
20+
"SA",
21+
"ES",
22+
"SE",
23+
"TR",
24+
"AE",
25+
"UK",
26+
"US",
27+
]
28+
29+
130
class Country:
2-
AU = "AU"
3-
BE = "BE"
4-
BR = "BR"
5-
CA = "CA"
6-
FR = "FR"
7-
DE = "DE"
8-
IN = "IN"
9-
IT = "IT"
10-
JP = "JP"
11-
MX = "MX"
12-
NL = "NL"
13-
PL = "PL"
14-
SG = "SG"
15-
SA = "SA"
16-
ES = "ES"
17-
SE = "SE"
18-
TR = "TR"
19-
AE = "AE"
20-
UK = "UK"
21-
US = "US"
31+
"""Constants for supported Amazon countries.
32+
33+
Use these constants when specifying the country parameter.
34+
Example: AmazonApi(key, secret, tag, Country.ES)
35+
"""
36+
37+
AU: CountryCode = "AU"
38+
BE: CountryCode = "BE"
39+
BR: CountryCode = "BR"
40+
CA: CountryCode = "CA"
41+
FR: CountryCode = "FR"
42+
DE: CountryCode = "DE"
43+
IN: CountryCode = "IN"
44+
IT: CountryCode = "IT"
45+
JP: CountryCode = "JP"
46+
MX: CountryCode = "MX"
47+
NL: CountryCode = "NL"
48+
PL: CountryCode = "PL"
49+
SG: CountryCode = "SG"
50+
SA: CountryCode = "SA"
51+
ES: CountryCode = "ES"
52+
SE: CountryCode = "SE"
53+
TR: CountryCode = "TR"
54+
AE: CountryCode = "AE"
55+
UK: CountryCode = "UK"
56+
US: CountryCode = "US"
2257

2358

24-
REGIONS = {
59+
REGIONS: dict[str, str] = {
2560
"AU": "us-west-2",
2661
"BE": "eu-west-1",
2762
"BR": "us-east-1",
@@ -45,7 +80,7 @@ class Country:
4580
}
4681

4782

48-
DOMAINS = {
83+
DOMAINS: dict[str, str] = {
4984
"AU": "com.au",
5085
"BE": "com.be",
5186
"BR": "com.br",

pyproject.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ exclude = [
4040
]
4141

4242
[tool.mypy]
43-
python_version = "3.7"
43+
python_version = "3.9"
4444
ignore_missing_imports = true
4545
no_implicit_optional = true
4646
strict_equality = true

setup.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
1+
from pathlib import Path
2+
13
import setuptools
24

3-
with open("README.md", encoding="utf8") as fh:
5+
with Path("README.md").open(encoding="utf8") as fh:
46
long_description = fh.read()
57

68
setuptools.setup(
@@ -20,5 +22,5 @@
2022
"License :: OSI Approved :: MIT License",
2123
"Operating System :: OS Independent",
2224
],
23-
python_requires=">=3.7",
25+
python_requires=">=3.9",
2426
)

0 commit comments

Comments
 (0)