Skip to content

Commit 2a4f467

Browse files
authored
chore: Remove "type: ignore" in samtranslator/translator (#2947)
1 parent a8d12ec commit 2a4f467

File tree

14 files changed

+93
-60
lines changed

14 files changed

+93
-60
lines changed

bin/sam-translate.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,7 @@ def transform_template(input_file_path, output_file_path): # type: ignore[no-un
106106
sam_template = yaml_parse(f) # type: ignore[no-untyped-call]
107107

108108
try:
109-
cloud_formation_template = transform(sam_template, {}, ManagedPolicyLoader(iam_client)) # type: ignore[no-untyped-call]
109+
cloud_formation_template = transform(sam_template, {}, ManagedPolicyLoader(iam_client))
110110
cloud_formation_template_prettified = json.dumps(cloud_formation_template, indent=1)
111111

112112
with open(output_file_path, "w") as f:

samtranslator/feature_toggle/feature_toggle.py

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import json
22
import logging
33
from abc import ABC, abstractmethod
4-
from typing import Any, Dict, cast
4+
from typing import Any, Dict, Optional, cast
55

66
import boto3
77
from botocore.config import Config
@@ -28,7 +28,13 @@ class FeatureToggle:
2828
"account-percentile": SimpleAccountPercentileDialup,
2929
}
3030

31-
def __init__(self, config_provider, stage, account_id, region): # type: ignore[no-untyped-def]
31+
def __init__(
32+
self,
33+
config_provider: "FeatureToggleConfigProvider",
34+
stage: Optional[str],
35+
account_id: Optional[str],
36+
region: Optional[str],
37+
) -> None:
3238
self.feature_config = config_provider.config
3339
self.stage = stage
3440
self.account_id = account_id

samtranslator/metrics/method_decorator.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ class MetricsMethodWrapperSingleton:
2323
This singleton will be alive until lambda receives shutdown event
2424
"""
2525

26-
_DUMMY_INSTANCE = Metrics("ServerlessTransform", DummyMetricsPublisher()) # type: ignore[no-untyped-call, no-untyped-call]
26+
_DUMMY_INSTANCE = Metrics("ServerlessTransform", DummyMetricsPublisher())
2727
_METRICS_INSTANCE = _DUMMY_INSTANCE
2828

2929
@staticmethod

samtranslator/metrics/metrics.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
import logging
55
from abc import ABC, abstractmethod
66
from datetime import datetime
7-
from typing import Any, Dict
7+
from typing import Any, Dict, List, Optional
88

99
LOG = logging.getLogger(__name__)
1010

@@ -13,7 +13,7 @@ class MetricsPublisher(ABC):
1313
"""Interface for all MetricPublishers"""
1414

1515
@abstractmethod
16-
def publish(self, namespace, metrics): # type: ignore[no-untyped-def]
16+
def publish(self, namespace: str, metrics: List["MetricDatum"]) -> None:
1717
"""
1818
Abstract method to publish all metrics to CloudWatch
1919
@@ -117,15 +117,17 @@ def get_metric_data(self) -> Dict[str, Any]:
117117

118118

119119
class Metrics:
120-
def __init__(self, namespace="ServerlessTransform", metrics_publisher=None): # type: ignore[no-untyped-def]
120+
def __init__(
121+
self, namespace: str = "ServerlessTransform", metrics_publisher: Optional[MetricsPublisher] = None
122+
) -> None:
121123
"""
122124
Constructor
123125
124126
:param namespace: namespace under which all metrics will be published
125127
:param metrics_publisher: publisher to publish all metrics
126128
"""
127129
self.metrics_publisher = metrics_publisher if metrics_publisher else DummyMetricsPublisher()
128-
self.metrics_cache = {}
130+
self.metrics_cache: Dict[str, List[MetricDatum]] = {}
129131
self.namespace = namespace
130132

131133
def __del__(self) -> None:

samtranslator/parser/parser.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,13 @@
11
import logging
2+
from typing import Any, Dict
23

34
from samtranslator.model.exceptions import (
45
InvalidDocumentException,
56
InvalidResourceAttributeTypeException,
67
InvalidTemplateException,
78
)
89
from samtranslator.plugins import LifeCycleEvents
10+
from samtranslator.plugins.sam_plugins import SamPlugins
911
from samtranslator.public.sdk.template import SamTemplate
1012
from samtranslator.validator.validator import SamTemplateValidator
1113
from samtranslator.validator.value_validator import sam_expect
@@ -17,7 +19,7 @@ class Parser:
1719
def __init__(self) -> None:
1820
pass
1921

20-
def parse(self, sam_template, parameter_values, sam_plugins): # type: ignore[no-untyped-def]
22+
def parse(self, sam_template: Dict[str, Any], parameter_values: Dict[str, Any], sam_plugins: SamPlugins) -> None:
2123
self._validate(sam_template, parameter_values) # type: ignore[no-untyped-call]
2224
sam_plugins.act(LifeCycleEvents.before_transform_template, sam_template)
2325

samtranslator/plugins/application/serverless_app_plugin.py

Lines changed: 24 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,10 @@
22
import json
33
import logging
44
from time import sleep
5-
from typing import Any, Dict, Tuple
5+
from typing import Any, Dict, List, Optional, Tuple
66

77
import boto3
8+
from botocore.client import BaseClient
89
from botocore.config import Config
910
from botocore.exceptions import ClientError, EndpointConnectionError
1011

@@ -50,7 +51,13 @@ class ServerlessAppPlugin(BasePlugin):
5051
LOCATION_KEY = "Location"
5152
TEMPLATE_URL_KEY = "TemplateUrl"
5253

53-
def __init__(self, sar_client=None, wait_for_template_active_status=False, validate_only=False, parameters=None): # type: ignore[no-untyped-def]
54+
def __init__(
55+
self,
56+
sar_client: Optional[BaseClient] = None,
57+
wait_for_template_active_status: bool = False,
58+
validate_only: bool = False,
59+
parameters: Optional[Dict[str, Any]] = None,
60+
):
5461
"""
5562
Initialize the plugin.
5663
@@ -62,9 +69,9 @@ def __init__(self, sar_client=None, wait_for_template_active_status=False, valid
6269
super().__init__()
6370
if parameters is None:
6471
parameters = {}
65-
self._applications = {}
66-
self._in_progress_templates = []
67-
self._sar_client = sar_client
72+
self._applications: Dict[Tuple[str, str], Any] = {}
73+
self._in_progress_templates: List[Tuple[str, str]] = []
74+
self.__sar_client = sar_client
6875
self._wait_for_template_active_status = wait_for_template_active_status
6976
self._validate_only = validate_only
7077
self._parameters = parameters
@@ -75,6 +82,15 @@ def __init__(self, sar_client=None, wait_for_template_active_status=False, valid
7582
message = "Cannot set both validate_only and wait_for_template_active_status flags to True."
7683
raise InvalidPluginException(ServerlessAppPlugin.__name__, message)
7784

85+
@property
86+
def _sar_client(self) -> BaseClient:
87+
# Lazy initialization of the client- create it when it is needed
88+
if not self.__sar_client:
89+
# a SAR call could take a while to finish, leaving the read_timeout default (60s).
90+
client_config = Config(connect_timeout=BOTO3_CONNECT_TIMEOUT)
91+
self.__sar_client = boto3.client("serverlessrepo", config=client_config)
92+
return self.__sar_client
93+
7894
@staticmethod
7995
def _make_app_key(app_id: Any, semver: Any) -> Tuple[str, str]:
8096
"""Generate a key that is always hashable."""
@@ -127,11 +143,6 @@ def on_before_transform_template(self, template_dict): # type: ignore[no-untype
127143
raise InvalidResourceException(
128144
logical_id, "Serverless Application Repository is not available in this region."
129145
)
130-
# Lazy initialization of the client- create it when it is needed
131-
if not self._sar_client:
132-
# a SAR call could take a while to finish, leaving the read_timeout default (60s).
133-
client_config = Config(connect_timeout=BOTO3_CONNECT_TIMEOUT)
134-
self._sar_client = boto3.client("serverlessrepo", config=client_config)
135146
self._make_service_call_with_retry(service_call, app_id, semver, key, logical_id) # type: ignore[no-untyped-call]
136147
except InvalidResourceException as e:
137148
# Catch all InvalidResourceExceptions, raise those in the before_resource_transform target.
@@ -421,17 +432,17 @@ def _resource_is_supported(self, resource_type): # type: ignore[no-untyped-def]
421432
return resource_type == self.SUPPORTED_RESOURCE_TYPE
422433

423434
def _get_application(self, app_id, semver): # type: ignore[no-untyped-def]
424-
return self._sar_client.get_application(
435+
return self._sar_client.get_application( # type: ignore[attr-defined]
425436
ApplicationId=self._sanitize_sar_str_param(app_id), SemanticVersion=self._sanitize_sar_str_param(semver) # type: ignore[no-untyped-call]
426437
)
427438

428439
def _create_cfn_template(self, app_id, semver): # type: ignore[no-untyped-def]
429-
return self._sar_client.create_cloud_formation_template(
440+
return self._sar_client.create_cloud_formation_template( # type: ignore[attr-defined]
430441
ApplicationId=self._sanitize_sar_str_param(app_id), SemanticVersion=self._sanitize_sar_str_param(semver) # type: ignore[no-untyped-call]
431442
)
432443

433444
def _get_cfn_template(self, app_id, template_id): # type: ignore[no-untyped-def]
434-
return self._sar_client.get_cloud_formation_template(
445+
return self._sar_client.get_cloud_formation_template( # type: ignore[attr-defined]
435446
ApplicationId=self._sanitize_sar_str_param(app_id), # type: ignore[no-untyped-call]
436447
TemplateId=self._sanitize_sar_str_param(template_id), # type: ignore[no-untyped-call]
437448
)

samtranslator/plugins/policies/policy_templates_plugin.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
from samtranslator.model.resource_policies import PolicyTypes, ResourcePolicies
55
from samtranslator.plugins import BasePlugin
66
from samtranslator.policy_template_processor.exceptions import InsufficientParameterValues, InvalidParameterValues
7+
from samtranslator.policy_template_processor.processor import PolicyTemplatesProcessor
78

89

910
class PolicyTemplatesForResourcePlugin(BasePlugin):
@@ -17,7 +18,7 @@ class PolicyTemplatesForResourcePlugin(BasePlugin):
1718
_plugin_name = ""
1819
SUPPORTED_RESOURCE_TYPE = {"AWS::Serverless::Function", "AWS::Serverless::StateMachine"}
1920

20-
def __init__(self, policy_template_processor): # type: ignore[no-untyped-def]
21+
def __init__(self, policy_template_processor: PolicyTemplatesProcessor) -> None:
2122
"""
2223
Initialize the plugin.
2324

samtranslator/region_configuration.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ def is_service_supported(cls, service, region=None): # type: ignore[no-untyped-
4747
# need to handle when region is None so that it won't break
4848
if region is None:
4949
if ArnGenerator.BOTO_SESSION_REGION_NAME is not None:
50-
region = ArnGenerator.BOTO_SESSION_REGION_NAME # type: ignore[unreachable]
50+
region = ArnGenerator.BOTO_SESSION_REGION_NAME
5151
else:
5252
raise NoRegionFound("AWS Region cannot be found")
5353

samtranslator/sdk/parameter.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
import copy
2-
from typing import Any, Dict
2+
from typing import Any, Dict, Optional
33

44
import boto3
5+
from boto3 import Session
56

67
from samtranslator.translator.arn_generator import ArnGenerator, NoRegionFound
78

@@ -64,7 +65,7 @@ def add_default_parameter_values(self, sam_template: Dict[str, Any]) -> Any:
6465

6566
return None
6667

67-
def add_pseudo_parameter_values(self, session=None): # type: ignore[no-untyped-def]
68+
def add_pseudo_parameter_values(self, session: Optional[Session] = None) -> None:
6869
"""
6970
Add pseudo parameter values
7071
:return: parameter values that have pseudo parameter in it

samtranslator/translator/arn_generator.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ def _region_to_partition(region: str) -> str:
3030

3131

3232
class ArnGenerator:
33-
BOTO_SESSION_REGION_NAME = None
33+
BOTO_SESSION_REGION_NAME: Optional[str] = None
3434

3535
@classmethod
3636
def generate_arn(

0 commit comments

Comments
 (0)