Skip to content

Commit 8817b26

Browse files
authored
Minor cleanups (#1190)
Make a refurn run on the code base.
1 parent 3431088 commit 8817b26

File tree

6 files changed

+36
-56
lines changed

6 files changed

+36
-56
lines changed

.generator/src/generator/templates/api_client.j2

Lines changed: 6 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -131,8 +131,7 @@ class ApiClient(object):
131131

132132
if return_http_data_only:
133133
return return_data
134-
else:
135-
return (return_data, response.status, response.getheaders())
134+
return (return_data, response.status, response.getheaders())
136135

137136
def parameters_to_multipart(self, params, collection_types):
138137
"""Get parameters as list of tuples, formatting as json if value is collection_types.
@@ -170,7 +169,7 @@ class ApiClient(object):
170169
:return: The serialized form of data.
171170
"""
172171
if isinstance(obj, (ModelNormal, ModelComposed)):
173-
return {key: cls.sanitize_for_serialization(val) for key, val in model_to_dict(obj, serialize=True).items()}
172+
return {key: cls.sanitize_for_serialization(val) for key, val in model_to_dict(obj).items()}
174173
elif isinstance(obj, io.IOBase):
175174
return cls.get_file_data_and_close_file(obj)
176175
elif isinstance(obj, (str, int, float, bool)) or obj is None:
@@ -306,7 +305,7 @@ class ApiClient(object):
306305

307306
# post parameters
308307
if post_params or files:
309-
post_params = post_params if post_params else []
308+
post_params = post_params or []
310309
post_params = self.sanitize_for_serialization(post_params)
311310
post_params = self.parameters_to_tuples(post_params, collection_formats)
312311
post_params.extend(self.files_parameters(files))
@@ -338,7 +337,7 @@ class ApiClient(object):
338337
check_type,
339338
)
340339

341-
def parameters_to_tuples(self, params, collection_formats) -> List[Tuple[str, str]]:
340+
def parameters_to_tuples(self, params, collection_formats) -> List[Tuple[str, Any]]:
342341
"""Get parameters as list of tuples, formatting collections.
343342

344343
:param params: Parameters as dict or list of two-tuples
@@ -426,8 +425,7 @@ class ApiClient(object):
426425

427426
if "application/json" in content_types or "*/*" in content_types:
428427
return "application/json"
429-
else:
430-
return content_types[0]
428+
return content_types[0]
431429

432430

433431
class ThreadedApiClient(ApiClient):
@@ -552,8 +550,7 @@ class AsyncApiClient(ApiClient):
552550

553551
if return_http_data_only:
554552
return return_data
555-
else:
556-
return (return_data, response.status_code, response.headers)
553+
return (return_data, response.status_code, response.headers)
557554

558555

559556
class Endpoint(object):

.generator/src/generator/templates/model_utils.j2

Lines changed: 9 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
{% include "api_info.j2" %}
22

3+
from contextlib import suppress
34
from datetime import date, datetime
45
import enum
56
import inspect
@@ -310,7 +311,7 @@ class ModelSimple(OpenApiModel):
310311
return self.get(name)
311312

312313
raise ApiAttributeError(
313-
"{0} has no attribute '{1}'".format(type(self).__name__, name), [e for e in [self._path_to_item, name] if e]
314+
"{0} has no attribute '{1}'".format(type(self).__name__, name), [e for e in (self._path_to_item, name) if e]
314315
)
315316

316317
def __contains__(self, name):
@@ -371,7 +372,7 @@ class ModelNormal(OpenApiModel):
371372
return self.get(name)
372373

373374
raise ApiAttributeError(
374-
"{0} has no attribute '{1}'".format(type(self).__name__, name), [e for e in [self._path_to_item, name] if e]
375+
"{0} has no attribute '{1}'".format(type(self).__name__, name), [e for e in (self._path_to_item, name) if e]
375376
)
376377

377378
def __contains__(self, name):
@@ -515,7 +516,7 @@ class ModelComposed(OpenApiModel):
515516
"Values stored for property {0} in {1} differ when looking "
516517
"at self and self's composed instances. All values must be "
517518
"the same".format(name, type(self).__name__),
518-
[e for e in [self._path_to_item, name] if e],
519+
[e for e in (self._path_to_item, name) if e],
519520
)
520521

521522
def __getitem__(self, name):
@@ -524,7 +525,7 @@ class ModelComposed(OpenApiModel):
524525
if value is self.__unset_attribute_value__:
525526
raise ApiAttributeError(
526527
"{0} has no attribute '{1}'".format(type(self).__name__, name),
527-
[e for e in [self._path_to_item, name] if e],
528+
[e for e in (self._path_to_item, name) if e],
528529
)
529530
return value
530531

@@ -885,7 +886,7 @@ def order_response_types(required_types):
885886
return COERCION_INDEX_BY_TYPE[class_or_instance]
886887
raise ApiValueError("Unsupported type: %s" % class_or_instance)
887888

888-
sorted_types = sorted(required_types, key=lambda class_or_instance: index_getter(class_or_instance))
889+
sorted_types = sorted(required_types, key=index_getter)
889890
return sorted_types
890891

891892

@@ -1034,9 +1035,7 @@ def deserialize_primitive(data, klass, path_to_item):
10341035
# The string should be in iso8601 datetime format.
10351036
parsed_datetime = parse(data)
10361037
date_only = (
1037-
parsed_datetime.hour == 0
1038-
and parsed_datetime.minute == 0
1039-
and parsed_datetime.second == 0
1038+
parsed_datetime.hour == parsed_datetime.minute == parsed_datetime.second == 0
10401039
and parsed_datetime.tzinfo is None
10411040
and 8 <= len(data) <= 10
10421041
)
@@ -1289,7 +1288,6 @@ def validate_and_convert_types(
12891288
path_to_item,
12901289
configuration,
12911290
spec_property_naming,
1292-
key_type=False,
12931291
must_convert=True,
12941292
check_type=check_type,
12951293
)
@@ -1307,8 +1305,6 @@ def validate_and_convert_types(
13071305
path_to_item,
13081306
configuration,
13091307
spec_property_naming,
1310-
key_type=False,
1311-
must_convert=False,
13121308
check_type=check_type,
13131309
)
13141310

@@ -1506,7 +1502,7 @@ def get_oneof_instance(cls, model_kwargs, constant_kwargs, model_arg=None):
15061502

15071503
single_value_input = allows_single_value_input(oneof_class)
15081504

1509-
try:
1505+
with suppress(Exception):
15101506
if not single_value_input:
15111507
if constant_kwargs.get("_spec_property_naming"):
15121508
oneof_instance = oneof_class(
@@ -1531,8 +1527,6 @@ def get_oneof_instance(cls, model_kwargs, constant_kwargs, model_arg=None):
15311527
configuration=constant_kwargs.get("_configuration"),
15321528
)
15331529
oneof_instances.append(oneof_instance)
1534-
except Exception:
1535-
pass
15361530
if len(oneof_instances) != 1:
15371531
return UnparsedObject(**model_kwargs)
15381532
return oneof_instances[0]
@@ -1548,7 +1542,7 @@ def get_discarded_args(self, composed_instances, model_args):
15481542
# before __init__ was called
15491543
for instance in composed_instances:
15501544
all_keys = set(model_to_dict(instance, serialize=False).keys())
1551-
js_keys = model_to_dict(instance, serialize=True).keys()
1545+
js_keys = model_to_dict(instance).keys()
15521546
all_keys.update(js_keys)
15531547
discarded_keys = model_arg_keys - all_keys
15541548
discarded_args.update(discarded_keys)

.generator/src/generator/templates/rest.j2

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -100,7 +100,6 @@ class RESTClientObject:
100100
(connection, read) timeouts.
101101
"""
102102
method = method.upper()
103-
assert method in ["GET", "HEAD", "DELETE", "POST", "PUT", "PATCH", "OPTIONS"]
104103

105104
if post_params and body:
106105
raise ApiValueError("body parameter cannot be used with post_params parameter.")
@@ -117,9 +116,9 @@ class RESTClientObject:
117116

118117
try:
119118
# For `POST`, `PUT`, `PATCH`, `OPTIONS`, `DELETE`
120-
if method in ["POST", "PUT", "PATCH", "OPTIONS", "DELETE"]:
119+
if method in ("POST", "PUT", "PATCH", "OPTIONS", "DELETE"):
121120
# Only set a default Content-Type for POST, PUT, PATCH and OPTIONS requests
122-
if (method != "DELETE") and ("Content-Type" not in headers):
121+
if method != "DELETE" and "Content-Type" not in headers:
123122
headers["Content-Type"] = "application/json"
124123
if query_params:
125124
url += "?" + urlencode(query_params)
@@ -172,7 +171,7 @@ class RESTClientObject:
172171
# Pass a `string` parameter directly in the body to support
173172
# other content types than Json when `body` argument is
174173
# provided in serialized form
175-
elif isinstance(body, str) or isinstance(body, bytes):
174+
elif isinstance(body, (str, bytes)):
176175
request_body = body
177176
r = self.pool_manager.request(
178177
method,

src/datadog_api_client/api_client.py

Lines changed: 6 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -132,8 +132,7 @@ def _call_api(
132132

133133
if return_http_data_only:
134134
return return_data
135-
else:
136-
return (return_data, response.status, response.getheaders())
135+
return (return_data, response.status, response.getheaders())
137136

138137
def parameters_to_multipart(self, params, collection_types):
139138
"""Get parameters as list of tuples, formatting as json if value is collection_types.
@@ -171,7 +170,7 @@ def sanitize_for_serialization(cls, obj):
171170
:return: The serialized form of data.
172171
"""
173172
if isinstance(obj, (ModelNormal, ModelComposed)):
174-
return {key: cls.sanitize_for_serialization(val) for key, val in model_to_dict(obj, serialize=True).items()}
173+
return {key: cls.sanitize_for_serialization(val) for key, val in model_to_dict(obj).items()}
175174
elif isinstance(obj, io.IOBase):
176175
return cls.get_file_data_and_close_file(obj)
177176
elif isinstance(obj, (str, int, float, bool)) or obj is None:
@@ -305,7 +304,7 @@ def call_api(
305304

306305
# post parameters
307306
if post_params or files:
308-
post_params = post_params if post_params else []
307+
post_params = post_params or []
309308
post_params = self.sanitize_for_serialization(post_params)
310309
post_params = self.parameters_to_tuples(post_params, collection_formats)
311310
post_params.extend(self.files_parameters(files))
@@ -337,7 +336,7 @@ def call_api(
337336
check_type,
338337
)
339338

340-
def parameters_to_tuples(self, params, collection_formats) -> List[Tuple[str, str]]:
339+
def parameters_to_tuples(self, params, collection_formats) -> List[Tuple[str, Any]]:
341340
"""Get parameters as list of tuples, formatting collections.
342341
343342
:param params: Parameters as dict or list of two-tuples
@@ -425,8 +424,7 @@ def select_header_content_type(self, content_types):
425424

426425
if "application/json" in content_types or "*/*" in content_types:
427426
return "application/json"
428-
else:
429-
return content_types[0]
427+
return content_types[0]
430428

431429

432430
class ThreadedApiClient(ApiClient):
@@ -551,8 +549,7 @@ async def _call_api(
551549

552550
if return_http_data_only:
553551
return return_data
554-
else:
555-
return (return_data, response.status_code, response.headers)
552+
return (return_data, response.status_code, response.headers)
556553

557554

558555
class Endpoint(object):

src/datadog_api_client/model_utils.py

Lines changed: 9 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
# This product includes software developed at Datadog (https://www.datadoghq.com/).
33
# Copyright 2019-Present Datadog, Inc.
44

5+
from contextlib import suppress
56
from datetime import date, datetime
67
import enum
78
import inspect
@@ -312,7 +313,7 @@ def __getitem__(self, name):
312313
return self.get(name)
313314

314315
raise ApiAttributeError(
315-
"{0} has no attribute '{1}'".format(type(self).__name__, name), [e for e in [self._path_to_item, name] if e]
316+
"{0} has no attribute '{1}'".format(type(self).__name__, name), [e for e in (self._path_to_item, name) if e]
316317
)
317318

318319
def __contains__(self, name):
@@ -373,7 +374,7 @@ def __getitem__(self, name):
373374
return self.get(name)
374375

375376
raise ApiAttributeError(
376-
"{0} has no attribute '{1}'".format(type(self).__name__, name), [e for e in [self._path_to_item, name] if e]
377+
"{0} has no attribute '{1}'".format(type(self).__name__, name), [e for e in (self._path_to_item, name) if e]
377378
)
378379

379380
def __contains__(self, name):
@@ -517,7 +518,7 @@ def get(self, name, default=None):
517518
"Values stored for property {0} in {1} differ when looking "
518519
"at self and self's composed instances. All values must be "
519520
"the same".format(name, type(self).__name__),
520-
[e for e in [self._path_to_item, name] if e],
521+
[e for e in (self._path_to_item, name) if e],
521522
)
522523

523524
def __getitem__(self, name):
@@ -526,7 +527,7 @@ def __getitem__(self, name):
526527
if value is self.__unset_attribute_value__:
527528
raise ApiAttributeError(
528529
"{0} has no attribute '{1}'".format(type(self).__name__, name),
529-
[e for e in [self._path_to_item, name] if e],
530+
[e for e in (self._path_to_item, name) if e],
530531
)
531532
return value
532533

@@ -887,7 +888,7 @@ def index_getter(class_or_instance):
887888
return COERCION_INDEX_BY_TYPE[class_or_instance]
888889
raise ApiValueError("Unsupported type: %s" % class_or_instance)
889890

890-
sorted_types = sorted(required_types, key=lambda class_or_instance: index_getter(class_or_instance))
891+
sorted_types = sorted(required_types, key=index_getter)
891892
return sorted_types
892893

893894

@@ -1036,9 +1037,7 @@ def deserialize_primitive(data, klass, path_to_item):
10361037
# The string should be in iso8601 datetime format.
10371038
parsed_datetime = parse(data)
10381039
date_only = (
1039-
parsed_datetime.hour == 0
1040-
and parsed_datetime.minute == 0
1041-
and parsed_datetime.second == 0
1040+
parsed_datetime.hour == parsed_datetime.minute == parsed_datetime.second == 0
10421041
and parsed_datetime.tzinfo is None
10431042
and 8 <= len(data) <= 10
10441043
)
@@ -1291,7 +1290,6 @@ def validate_and_convert_types(
12911290
path_to_item,
12921291
configuration,
12931292
spec_property_naming,
1294-
key_type=False,
12951293
must_convert=True,
12961294
check_type=check_type,
12971295
)
@@ -1309,8 +1307,6 @@ def validate_and_convert_types(
13091307
path_to_item,
13101308
configuration,
13111309
spec_property_naming,
1312-
key_type=False,
1313-
must_convert=False,
13141310
check_type=check_type,
13151311
)
13161312

@@ -1508,7 +1504,7 @@ def get_oneof_instance(cls, model_kwargs, constant_kwargs, model_arg=None):
15081504

15091505
single_value_input = allows_single_value_input(oneof_class)
15101506

1511-
try:
1507+
with suppress(Exception):
15121508
if not single_value_input:
15131509
if constant_kwargs.get("_spec_property_naming"):
15141510
oneof_instance = oneof_class(
@@ -1533,8 +1529,6 @@ def get_oneof_instance(cls, model_kwargs, constant_kwargs, model_arg=None):
15331529
configuration=constant_kwargs.get("_configuration"),
15341530
)
15351531
oneof_instances.append(oneof_instance)
1536-
except Exception:
1537-
pass
15381532
if len(oneof_instances) != 1:
15391533
return UnparsedObject(**model_kwargs)
15401534
return oneof_instances[0]
@@ -1550,7 +1544,7 @@ def get_discarded_args(self, composed_instances, model_args):
15501544
# before __init__ was called
15511545
for instance in composed_instances:
15521546
all_keys = set(model_to_dict(instance, serialize=False).keys())
1553-
js_keys = model_to_dict(instance, serialize=True).keys()
1547+
js_keys = model_to_dict(instance).keys()
15541548
all_keys.update(js_keys)
15551549
discarded_keys = model_arg_keys - all_keys
15561550
discarded_args.update(discarded_keys)

src/datadog_api_client/rest.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -102,7 +102,6 @@ def request(
102102
(connection, read) timeouts.
103103
"""
104104
method = method.upper()
105-
assert method in ["GET", "HEAD", "DELETE", "POST", "PUT", "PATCH", "OPTIONS"]
106105

107106
if post_params and body:
108107
raise ApiValueError("body parameter cannot be used with post_params parameter.")
@@ -119,9 +118,9 @@ def request(
119118

120119
try:
121120
# For `POST`, `PUT`, `PATCH`, `OPTIONS`, `DELETE`
122-
if method in ["POST", "PUT", "PATCH", "OPTIONS", "DELETE"]:
121+
if method in ("POST", "PUT", "PATCH", "OPTIONS", "DELETE"):
123122
# Only set a default Content-Type for POST, PUT, PATCH and OPTIONS requests
124-
if (method != "DELETE") and ("Content-Type" not in headers):
123+
if method != "DELETE" and "Content-Type" not in headers:
125124
headers["Content-Type"] = "application/json"
126125
if query_params:
127126
url += "?" + urlencode(query_params)
@@ -174,7 +173,7 @@ def request(
174173
# Pass a `string` parameter directly in the body to support
175174
# other content types than Json when `body` argument is
176175
# provided in serialized form
177-
elif isinstance(body, str) or isinstance(body, bytes):
176+
elif isinstance(body, (str, bytes)):
178177
request_body = body
179178
r = self.pool_manager.request(
180179
method,

0 commit comments

Comments
 (0)