Skip to content

Commit 2de3c57

Browse files
author
Adam Gray
committed
Type checkiing improvements
1 parent 5583d86 commit 2de3c57

File tree

18 files changed

+68
-48
lines changed

18 files changed

+68
-48
lines changed

openapi_python_client/openapi_parser/openapi.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -236,14 +236,16 @@ def _iterate_properties() -> Generator[Property, None, None]:
236236

237237
@staticmethod
238238
def from_dict(d: Dict[str, Dict[str, Any]], /) -> OpenAPI:
239-
""" Create an OpenAPI from dict """
239+
""" Create an OpenAPI from dict
240+
:rtype: object
241+
"""
240242
schemas = Schema.dict(d["components"]["schemas"])
241243
endpoint_collections_by_tag = EndpointCollection.from_dict(d["paths"])
242244
enums = OpenAPI._check_enums(schemas.values(), endpoint_collections_by_tag.values())
243245

244246
return OpenAPI(
245247
title=d["info"]["title"],
246-
description=d["info"]["description"],
248+
description=d["info"].get("description"),
247249
version=d["info"]["version"],
248250
endpoint_collections_by_tag=endpoint_collections_by_tag,
249251
schemas=schemas,

openapi_python_client/openapi_parser/properties.py

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -167,7 +167,10 @@ def transform(self) -> str:
167167

168168
def constructor_from_dict(self, dict_name: str) -> str:
169169
""" How to load this property from a dict (used in generated model from_dict function """
170-
return f'{self.reference.class_name}({dict_name}["{self.name}"]) if "{self.name}" in {dict_name} else None'
170+
constructor = f'{self.reference.class_name}({dict_name}["{self.name}"])'
171+
if not self.required:
172+
constructor += f' if "{self.name}" in {dict_name} else None'
173+
return constructor
171174

172175
@staticmethod
173176
def values_from_list(l: List[str], /) -> Dict[str, str]:
@@ -208,15 +211,15 @@ def transform(self) -> str:
208211
class DictProperty(Property):
209212
""" Property that is a general Dict """
210213

211-
_type_string: ClassVar[str] = "Dict"
214+
_type_string: ClassVar[str] = "Dict[Any, Any]"
212215

213216

214217
_openapi_types_to_python_type_strings = {
215218
"string": "str",
216219
"number": "float",
217220
"integer": "int",
218221
"boolean": "bool",
219-
"object": "Dict",
222+
"object": "Dict[Any, Any]",
220223
}
221224

222225

openapi_python_client/openapi_parser/responses.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ def return_string(self) -> str:
3333

3434
def constructor(self) -> str:
3535
""" How the return value of this response should be constructed """
36-
return f"[{self.reference.class_name}.from_dict(item) for item in response.json()]"
36+
return f"[{self.reference.class_name}.from_dict(item) for item in cast(List[Dict[str, Any]], response.json())]"
3737

3838

3939
@dataclass
@@ -48,7 +48,7 @@ def return_string(self) -> str:
4848

4949
def constructor(self) -> str:
5050
""" How the return value of this response should be constructed """
51-
return f"{self.reference.class_name}.from_dict(response.json())"
51+
return f"{self.reference.class_name}.from_dict(cast(Dict[str, Any], response.json()))"
5252

5353

5454
@dataclass

openapi_python_client/templates/async_endpoint_module.pyi

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
from dataclasses import asdict
2-
from typing import Dict, List, Optional, Union
2+
from typing import Dict, List, Optional, Union, Any, cast
33

44
import httpx
55

@@ -60,8 +60,8 @@ async def {{ endpoint.name }}(
6060
{% endfor %}
6161
{% endif %}
6262

63-
with httpx.AsyncClient() as client:
64-
response = await client.{{ endpoint.method }}(
63+
async with httpx.AsyncClient() as _client:
64+
response = await _client.{{ endpoint.method }}(
6565
url=url,
6666
headers=client.get_headers(),
6767
{% if endpoint.form_body_reference %}

openapi_python_client/templates/endpoint_module.pyi

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
from dataclasses import asdict
2-
from typing import Dict, List, Optional, Union
2+
from typing import Dict, List, Optional, Union, Any, cast
33

44
import httpx
55

openapi_python_client/templates/model.pyi

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ from __future__ import annotations
22

33
from dataclasses import dataclass
44
from datetime import datetime
5-
from typing import Dict, List, Optional, cast
5+
from typing import Any, Dict, List, Optional, cast
66

77
{% for relative in schema.relative_imports %}
88
{{ relative }}
@@ -16,7 +16,7 @@ class {{ schema.reference.class_name }}:
1616
{{ property.to_string() }}
1717
{% endfor %}
1818

19-
def to_dict(self) -> Dict:
19+
def to_dict(self) -> Dict[str, Any]:
2020
return {
2121
{% for property in schema.required_properties %}
2222
"{{ property.name }}": self.{{ property.transform() }},
@@ -27,7 +27,7 @@ class {{ schema.reference.class_name }}:
2727
}
2828

2929
@staticmethod
30-
def from_dict(d: Dict) -> {{ schema.reference.class_name }}:
30+
def from_dict(d: Dict[str, Any]) -> {{ schema.reference.class_name }}:
3131
{% for property in schema.required_properties + schema.optional_properties %}
3232

3333
{% if property.constructor_template %}

tests/test_end_to_end/golden-master/my_test_api_client/api/default.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
from dataclasses import asdict
2-
from typing import Dict, List, Optional, Union
2+
from typing import Any, Dict, List, Optional, Union, cast
33

44
import httpx
55

@@ -19,6 +19,6 @@ def ping_ping_get(
1919
response = httpx.get(url=url, headers=client.get_headers(),)
2020

2121
if response.status_code == 200:
22-
return ABCResponse.from_dict(response.json())
22+
return ABCResponse.from_dict(cast(Dict[str, Any], response.json()))
2323
else:
2424
raise ApiResponseError(response=response)

tests/test_end_to_end/golden-master/my_test_api_client/api/users.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
from dataclasses import asdict
2-
from typing import Dict, List, Optional, Union
2+
from typing import Any, Dict, List, Optional, Union, cast
33

44
import httpx
55

@@ -25,8 +25,8 @@ def get_list_tests__get(
2525
response = httpx.get(url=url, headers=client.get_headers(), params=params,)
2626

2727
if response.status_code == 200:
28-
return [AModel.from_dict(item) for item in response.json()]
28+
return [AModel.from_dict(item) for item in cast(List[Dict[str, Any]], response.json())]
2929
if response.status_code == 422:
30-
return HTTPValidationError.from_dict(response.json())
30+
return HTTPValidationError.from_dict(cast(Dict[str, Any], response.json()))
3131
else:
3232
raise ApiResponseError(response=response)

tests/test_end_to_end/golden-master/my_test_api_client/async_api/default.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
from dataclasses import asdict
2-
from typing import Dict, List, Optional, Union
2+
from typing import Any, Dict, List, Optional, Union, cast
33

44
import httpx
55

@@ -16,10 +16,10 @@ async def ping_ping_get(
1616
""" A quick check to see if the system is running """
1717
url = f"{client.base_url}/ping"
1818

19-
with httpx.AsyncClient() as client:
20-
response = await client.get(url=url, headers=client.get_headers(),)
19+
async with httpx.AsyncClient() as _client:
20+
response = await _client.get(url=url, headers=client.get_headers(),)
2121

2222
if response.status_code == 200:
23-
return ABCResponse.from_dict(response.json())
23+
return ABCResponse.from_dict(cast(Dict[str, Any], response.json()))
2424
else:
2525
raise ApiResponseError(response=response)

tests/test_end_to_end/golden-master/my_test_api_client/async_api/users.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
from dataclasses import asdict
2-
from typing import Dict, List, Optional, Union
2+
from typing import Any, Dict, List, Optional, Union, cast
33

44
import httpx
55

@@ -22,12 +22,12 @@ async def get_list_tests__get(
2222
"statuses": statuses,
2323
}
2424

25-
with httpx.AsyncClient() as client:
26-
response = await client.get(url=url, headers=client.get_headers(), params=params,)
25+
async with httpx.AsyncClient() as _client:
26+
response = await _client.get(url=url, headers=client.get_headers(), params=params,)
2727

2828
if response.status_code == 200:
29-
return [AModel.from_dict(item) for item in response.json()]
29+
return [AModel.from_dict(item) for item in cast(List[Dict[str, Any]], response.json())]
3030
if response.status_code == 422:
31-
return HTTPValidationError.from_dict(response.json())
31+
return HTTPValidationError.from_dict(cast(Dict[str, Any], response.json()))
3232
else:
3333
raise ApiResponseError(response=response)

0 commit comments

Comments
 (0)