Skip to content

Commit 504f1b3

Browse files
authored
chore: Upgrade mypy to 1.0.0 and type hint cw_timer (#2890)
1 parent 0da8c8c commit 504f1b3

File tree

8 files changed

+47
-12
lines changed

8 files changed

+47
-12
lines changed

requirements/dev.txt

+1-1
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ black==20.8b1
2424
ruamel.yaml==0.17.21 # It can parse yaml while perserving comments
2525

2626
# type check
27-
mypy==0.971
27+
mypy~=1.0.0
2828

2929
# types
3030
boto3-stubs[appconfig,serverlessrepo]>=1.19.5,==1.*

samtranslator/feature_toggle/feature_toggle.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -127,7 +127,7 @@ def config(self) -> Dict[str, Any]:
127127
class FeatureToggleAppConfigConfigProvider(FeatureToggleConfigProvider):
128128
"""Feature toggle config provider which loads config from AppConfig."""
129129

130-
@cw_timer(prefix="External", name="AppConfig") # type: ignore[misc]
130+
@cw_timer(prefix="External", name="AppConfig")
131131
def __init__(self, application_id, environment_id, configuration_profile_id, app_config_client=None): # type: ignore[no-untyped-def]
132132
FeatureToggleConfigProvider.__init__(self)
133133
try:

samtranslator/metrics/method_decorator.py

+19-5
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,15 @@
44
import functools
55
import logging
66
from datetime import datetime
7-
from typing import Any, Callable, Optional, Union
7+
from typing import Callable, Optional, TypeVar, Union, overload
88

99
from samtranslator.metrics.metrics import DummyMetricsPublisher, Metrics
1010
from samtranslator.model import Resource
1111

1212
LOG = logging.getLogger(__name__)
1313

14+
_RT = TypeVar("_RT") # return value
15+
1416

1517
class MetricsMethodWrapperSingleton:
1618
"""
@@ -76,9 +78,21 @@ def _send_cw_metric(prefix, name, execution_time_ms, func, args): # type: ignor
7678
LOG.warning("Failed to add metrics", exc_info=e)
7779

7880

81+
@overload
82+
def cw_timer(
83+
*, name: Optional[str] = None, prefix: Optional[str] = None
84+
) -> Callable[[Callable[..., _RT]], Callable[..., _RT]]:
85+
...
86+
87+
88+
@overload
89+
def cw_timer(_func: Callable[..., _RT], name: Optional[str] = None, prefix: Optional[str] = None) -> Callable[..., _RT]:
90+
...
91+
92+
7993
def cw_timer(
80-
_func: Optional[Callable[..., Any]] = None, name: Optional[str] = None, prefix: Optional[str] = None
81-
) -> Union[Callable[..., Any], Callable[[Callable[..., Any]], Callable[..., Any]]]:
94+
_func: Optional[Callable[..., _RT]] = None, name: Optional[str] = None, prefix: Optional[str] = None
95+
) -> Union[Callable[..., _RT], Callable[[Callable[..., _RT]], Callable[..., _RT]]]:
8296
"""
8397
A method decorator, that will calculate execution time of the decorated method, and store this information as a
8498
metric in CloudWatch by calling the metrics singleton instance.
@@ -91,9 +105,9 @@ def cw_timer(
91105
If prefix is defined, it will be added in the beginning of what is been generated above
92106
"""
93107

94-
def cw_timer_decorator(func: Callable[..., Any]) -> Callable[..., Any]:
108+
def cw_timer_decorator(func: Callable[..., _RT]) -> Callable[..., _RT]:
95109
@functools.wraps(func)
96-
def wrapper_cw_timer(*args, **kwargs): # type: ignore[no-untyped-def]
110+
def wrapper_cw_timer(*args, **kwargs) -> _RT: # type: ignore[no-untyped-def]
97111
start_time = datetime.now()
98112

99113
exec_result = func(*args, **kwargs)

samtranslator/model/__init__.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
""" CloudFormation Resource serialization, deserialization, and validation """
22
import inspect
33
import re
4-
from abc import ABC, ABCMeta
4+
from abc import ABC, ABCMeta, abstractmethod
55
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
66

77
from samtranslator.intrinsics.resolver import IntrinsicsResolver
@@ -409,6 +409,7 @@ def resources_to_link(self, resources): # type: ignore[no-untyped-def]
409409
"""
410410
return {}
411411

412+
@abstractmethod
412413
def to_cloudformation(self, **kwargs: Any) -> List[Any]:
413414
"""Returns a list of Resource instances, representing vanilla CloudFormation resources, to which this macro
414415
expands. The caller should be able to update their template with the expanded resources by calling

samtranslator/model/api/http_api_generator.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -712,7 +712,7 @@ def _add_title(self) -> None:
712712
open_api_editor.add_title(self.name)
713713
self.definition_body = open_api_editor.openapi
714714

715-
@cw_timer(prefix="Generator", name="HttpApi") # type: ignore[misc]
715+
@cw_timer(prefix="Generator", name="HttpApi")
716716
def to_cloudformation(
717717
self, route53_record_set_groups: Dict[str, Route53RecordSetGroup]
718718
) -> Tuple[

samtranslator/model/eventsources/scheduler.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,7 @@ class SchedulerEventSource(ResourceMacro):
7373

7474
DEFAULT_FLEXIBLE_TIME_WINDOW = {"Mode": "OFF"}
7575

76-
@cw_timer(prefix=FUNCTION_EVETSOURCE_METRIC_PREFIX) # type: ignore
76+
@cw_timer(prefix=FUNCTION_EVETSOURCE_METRIC_PREFIX)
7777
def to_cloudformation(self, **kwargs: Dict[str, Any]) -> List[Resource]:
7878
"""Returns the Scheduler Schedule and an IAM role.
7979

samtranslator/model/sam_resources.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -1366,7 +1366,7 @@ def to_cloudformation(self, **kwargs): # type: ignore[no-untyped-def]
13661366
:returns: a list of vanilla CloudFormation Resources, to which this Function expands
13671367
:rtype: list
13681368
"""
1369-
resources = []
1369+
resources: List[Resource] = []
13701370
intrinsics_resolver = kwargs["intrinsics_resolver"]
13711371
self.CorsConfiguration = intrinsics_resolver.resolve_parameter_refs(self.CorsConfiguration)
13721372
self.Domain = intrinsics_resolver.resolve_parameter_refs(self.Domain)
@@ -1816,7 +1816,7 @@ class SamConnector(SamResourceMacro):
18161816
}
18171817

18181818
@cw_timer
1819-
def to_cloudformation(self, **kwargs: Any) -> List[Resource]: # type: ignore
1819+
def to_cloudformation(self, **kwargs: Any) -> List[Resource]:
18201820
resource_resolver: ResourceResolver = kwargs["resource_resolver"]
18211821
original_template = kwargs["original_template"]
18221822

tests/test_model.py

+20
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
from typing import Any, List
2+
13
import pytest
24

35
from unittest import TestCase
@@ -220,6 +222,9 @@ class NewSamResource(SamResourceMacro):
220222
property_types = {}
221223
referable_properties = {"prop1": "resource_type1", "prop2": "resource_type2", "prop3": "resource_type3"}
222224

225+
def to_cloudformation(self, **kwargs: Any) -> List[Any]:
226+
return []
227+
223228
sam_resource = NewSamResource("SamLogicalId")
224229

225230
cfn_resources = [self.ResourceType1("logicalId1"), self.ResourceType2("logicalId2")]
@@ -241,6 +246,9 @@ class NewSamResource(SamResourceMacro):
241246
property_types = {}
242247
referable_properties = {"prop1": "resource_type1", "prop2": "resource_type2", "prop3": "resource_type3"}
243248

249+
def to_cloudformation(self, **kwargs: Any) -> List[Any]:
250+
return []
251+
244252
sam_resource1 = NewSamResource("SamLogicalId1")
245253
sam_resource2 = NewSamResource("SamLogicalId2")
246254

@@ -267,6 +275,9 @@ class NewSamResource(SamResourceMacro):
267275
property_types = {}
268276
referable_properties = {"prop1": "foo", "prop2": "bar"}
269277

278+
def to_cloudformation(self, **kwargs: Any) -> List[Any]:
279+
return []
280+
270281
sam_resource = NewSamResource("SamLogicalId")
271282

272283
# None of the CFN resource types are in the referable list
@@ -282,6 +293,9 @@ class NewSamResource(SamResourceMacro):
282293
property_types = {}
283294
referable_properties = {}
284295

296+
def to_cloudformation(self, **kwargs: Any) -> List[Any]:
297+
return []
298+
285299
sam_resource = NewSamResource("SamLogicalId")
286300

287301
cfn_resources = [self.ResourceType1("logicalId1"), self.ResourceType2("logicalId2")]
@@ -296,6 +310,9 @@ class NewSamResource(SamResourceMacro):
296310
property_types = {}
297311
referable_properties = {"prop1": "resource_type1"}
298312

313+
def to_cloudformation(self, **kwargs: Any) -> List[Any]:
314+
return []
315+
299316
sam_resource = NewSamResource("SamLogicalId")
300317

301318
cfn_resources = []
@@ -310,6 +327,9 @@ class NewSamResource(SamResourceMacro):
310327
property_types = {}
311328
referable_properties = {"prop1": "resource_type1"}
312329

330+
def to_cloudformation(self, **kwargs: Any) -> List[Any]:
331+
return []
332+
313333
sam_resource = NewSamResource("SamLogicalId")
314334

315335
cfn_resources = [self.ResourceType1("logicalId1")]

0 commit comments

Comments
 (0)