Skip to content

Commit 8b227cf

Browse files
committed
pylock: factor out _get_list
1 parent 98ea245 commit 8b227cf

File tree

1 file changed

+22
-11
lines changed

1 file changed

+22
-11
lines changed

src/pip/_internal/models/pylock.py

Lines changed: 22 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,22 @@ def _get_required(d: Dict[str, Any], expected_type: Type[T], key: str) -> T:
9494
return value
9595

9696

97+
def _get_list(
98+
d: Dict[str, Any], expected_item_type: Type[T], key: str
99+
) -> Optional[List[T]]:
100+
"""Get list value from dictionary and verify expected items type."""
101+
value = _get(d, list, key)
102+
if value is None:
103+
return None
104+
for i, item in enumerate(value):
105+
if not isinstance(item, expected_item_type):
106+
raise PylockValidationError(
107+
f"Item {i} of {key!r} has unexpected type {type(item).__name__} "
108+
f"(expected {expected_item_type.__name__})"
109+
)
110+
return value
111+
112+
97113
def _get_as(
98114
d: Dict[str, Any],
99115
expected_type: Type[T],
@@ -129,23 +145,18 @@ def _get_required_as(
129145

130146
def _get_list_as(
131147
d: Dict[str, Any],
132-
expected_type: Type[T],
133-
target_type: Type[SingleArgConstructorT],
148+
expected_item_type: Type[T],
149+
target_item_type: Type[SingleArgConstructorT],
134150
key: str,
135151
) -> Optional[List[SingleArgConstructorT]]:
136152
"""Get list value from dictionary and verify expected items type."""
137-
value = _get(d, list, key)
153+
value = _get_list(d, expected_item_type, key)
138154
if value is None:
139155
return None
140156
result = []
141157
for i, item in enumerate(value):
142-
if not isinstance(item, expected_type):
143-
raise PylockValidationError(
144-
f"Item {i} of {key!r} has unexpected type {type(item).__name__} "
145-
f"(expected {expected_type.__name__})"
146-
)
147158
try:
148-
result.append(target_type(item))
159+
result.append(target_item_type(item))
149160
except Exception as e:
150161
raise PylockValidationError(f"Error in item {i} of {key!r}: {e}") from e
151162
return result
@@ -165,7 +176,7 @@ def _get_object(
165176

166177

167178
def _get_list_of_objects(
168-
d: Dict[str, Any], target_type: Type[FromDictProtocolT], key: str
179+
d: Dict[str, Any], target_item_type: Type[FromDictProtocolT], key: str
169180
) -> Optional[List[FromDictProtocolT]]:
170181
"""Get list value from dictionary and convert items to dataclass."""
171182
value = _get(d, list, key)
@@ -176,7 +187,7 @@ def _get_list_of_objects(
176187
if not isinstance(item, dict):
177188
raise PylockValidationError(f"Item {i} of {key!r} is not a table")
178189
try:
179-
result.append(target_type.from_dict(item))
190+
result.append(target_item_type.from_dict(item))
180191
except Exception as e:
181192
raise PylockValidationError(f"Error in item {i} of {key!r}: {e}") from e
182193
return result

0 commit comments

Comments
 (0)