Skip to content

Commit d74a89c

Browse files
authored
Type Ignore Fixes Part Four (#2757)
Co-authored-by: Gavin Zhang <[email protected]>
1 parent 8066335 commit d74a89c

File tree

5 files changed

+65
-43
lines changed

5 files changed

+65
-43
lines changed

samtranslator/model/__init__.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -193,7 +193,7 @@ def from_dict(cls, logical_id, resource_dict, relative_id=None, sam_plugins=None
193193
if attr in resource_dict:
194194
resource.set_resource_attribute(attr, resource_dict[attr])
195195

196-
resource.validate_properties() # type: ignore[no-untyped-call]
196+
resource.validate_properties()
197197
return resource
198198

199199
@classmethod
@@ -231,7 +231,7 @@ def _validate_resource_dict(cls, logical_id, resource_dict): # type: ignore[no-
231231
if "Properties" in resource_dict and not isinstance(resource_dict["Properties"], dict):
232232
raise InvalidResourceException(logical_id, "Properties of a resource must be an object.")
233233

234-
def to_dict(self): # type: ignore[no-untyped-def]
234+
def to_dict(self) -> Dict[str, Dict[str, Any]]:
235235
"""Validates that the required properties for this Resource have been provided, then returns a dict
236236
corresponding to the given Resource object. This dict will take the format of a single entry in the Resources
237237
section of a CloudFormation template, and will take the following format. ::
@@ -252,7 +252,7 @@ def to_dict(self): # type: ignore[no-untyped-def]
252252
:rtype: dict
253253
:raises TypeError: if a required property is missing from this Resource
254254
"""
255-
self.validate_properties() # type: ignore[no-untyped-call]
255+
self.validate_properties()
256256

257257
resource_dict = self._generate_resource_dict() # type: ignore[no-untyped-call]
258258

@@ -300,7 +300,7 @@ def __setattr__(self, name, value): # type: ignore[no-untyped-def]
300300
),
301301
)
302302

303-
def validate_properties(self): # type: ignore[no-untyped-def]
303+
def validate_properties(self) -> None:
304304
"""Validates that the required properties for this Resource have been populated, and that all properties have
305305
valid values.
306306
@@ -523,7 +523,7 @@ class ResourceTypeResolver(object):
523523
"""ResourceTypeResolver maps Resource Types to Resource classes, e.g. AWS::Serverless::Function to
524524
samtranslator.model.sam_resources.SamFunction."""
525525

526-
def __init__(self, *modules): # type: ignore[no-untyped-def]
526+
def __init__(self, *modules: Any):
527527
"""Initializes the ResourceTypeResolver from the given modules.
528528
529529
:param modules: one or more Python modules containing Resource definitions

samtranslator/model/lambda_.py

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from typing import Optional, Dict, Any, List
1+
from typing import Optional, Dict, Any, List, Union
22
from samtranslator.model import PropertyType, Resource
33
from samtranslator.model.types import IS_DICT, is_type, one_of, IS_STR, list_of, any_type
44
from samtranslator.model.intrinsics import fnGetAtt, ref
@@ -152,6 +152,13 @@ class LambdaLayerVersion(Resource):
152152
"LicenseInfo": PropertyType(False, IS_STR),
153153
}
154154

155+
Content: Dict[str, Any]
156+
Description: Optional[Intrinsicable[str]]
157+
LayerName: Optional[Intrinsicable[str]]
158+
CompatibleArchitectures: Optional[List[Union[str, Dict[str, Any]]]]
159+
CompatibleRuntimes: Optional[List[Union[str, Dict[str, Any]]]]
160+
LicenseInfo: Optional[Intrinsicable[str]]
161+
155162
runtime_attrs = {"name": lambda self: ref(self.logical_id), "arn": lambda self: fnGetAtt(self.logical_id, "Arn")}
156163

157164

samtranslator/model/s3_utils/uri_parser.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from typing import Any, Dict, Optional
1+
from typing import Any, Dict, Optional, Union
22
from urllib.parse import urlparse, parse_qs
33
from samtranslator.model.exceptions import InvalidResourceException
44

@@ -62,7 +62,9 @@ def construct_image_code_object(image_uri, logical_id, property_name): # type:
6262
return {"ImageUri": image_uri}
6363

6464

65-
def construct_s3_location_object(location_uri, logical_id, property_name): # type: ignore[no-untyped-def]
65+
def construct_s3_location_object(
66+
location_uri: Union[str, Dict[str, Any]], logical_id: str, property_name: str
67+
) -> Dict[str, Any]:
6668
"""Constructs a Lambda `Code` or `Content` property, from the SAM `CodeUri` or `ContentUri` property.
6769
This follows the current scheme for Lambda Functions and LayerVersions.
6870

samtranslator/model/sam_resources.py

Lines changed: 46 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
""" SAM macro definitions """
22
import copy
3-
from typing import Any, cast, Dict, List, Optional, Tuple, Union
3+
from typing import Any, cast, Dict, List, Optional, Tuple, Union, Callable
44
from samtranslator.intrinsics.resolver import IntrinsicsResolver
55
from samtranslator.feature_toggle.feature_toggle import FeatureToggle
66
from samtranslator.model.connector.connector import (
@@ -167,7 +167,7 @@ class SamFunction(SamResourceMacro):
167167
SnapStart: Optional[Dict[str, Any]]
168168
FunctionUrlConfig: Optional[Dict[str, Any]]
169169

170-
event_resolver = ResourceTypeResolver( # type: ignore[no-untyped-call]
170+
event_resolver = ResourceTypeResolver(
171171
samtranslator.model.eventsources,
172172
samtranslator.model.eventsources.pull,
173173
samtranslator.model.eventsources.push,
@@ -191,9 +191,9 @@ class SamFunction(SamResourceMacro):
191191
"DestinationQueue": SQSQueue.resource_type,
192192
}
193193

194-
def resources_to_link(self, resources): # type: ignore[no-untyped-def]
194+
def resources_to_link(self, resources: Dict[str, Any]) -> Dict[str, Any]:
195195
try:
196-
return {"event_resources": self._event_resources_to_link(resources)} # type: ignore[no-untyped-call]
196+
return {"event_resources": self._event_resources_to_link(resources)}
197197
except InvalidEventException as e:
198198
raise InvalidResourceException(self.logical_id, e.message)
199199

@@ -260,7 +260,7 @@ def to_cloudformation(self, **kwargs): # type: ignore[no-untyped-def]
260260
feature_toggle,
261261
)
262262

263-
event_invoke_policies = []
263+
event_invoke_policies: List[Dict[str, Any]] = []
264264
if self.EventInvokeConfig:
265265
function_name = lambda_function.logical_id
266266
event_invoke_resources, event_invoke_policies = self._construct_event_invoke_config(
@@ -279,7 +279,7 @@ def to_cloudformation(self, **kwargs): # type: ignore[no-untyped-def]
279279
resources.append(execution_role)
280280

281281
try:
282-
resources += self._generate_event_resources( # type: ignore[no-untyped-call]
282+
resources += self._generate_event_resources(
283283
lambda_function,
284284
execution_role,
285285
kwargs["event_resources"],
@@ -291,7 +291,15 @@ def to_cloudformation(self, **kwargs): # type: ignore[no-untyped-def]
291291

292292
return resources
293293

294-
def _construct_event_invoke_config(self, function_name, alias_name, lambda_alias, intrinsics_resolver, conditions, event_invoke_config: Dict[str, Any]): # type: ignore[no-untyped-def]
294+
def _construct_event_invoke_config(
295+
self,
296+
function_name: str,
297+
alias_name: str,
298+
lambda_alias: Optional[LambdaAlias],
299+
intrinsics_resolver: IntrinsicsResolver,
300+
conditions: Any,
301+
event_invoke_config: Dict[str, Any],
302+
) -> Tuple[List[Any], List[Dict[str, Any]]]:
295303
"""
296304
Create a `AWS::Lambda::EventInvokeConfig` based on the input dict `EventInvokeConfig`
297305
"""
@@ -502,7 +510,7 @@ def _construct_lambda_function(self) -> LambdaFunction:
502510
lambda_function.VpcConfig = self.VpcConfig
503511
lambda_function.Role = self.Role
504512
lambda_function.Environment = self.Environment
505-
lambda_function.Code = self._construct_code_dict() # type: ignore[no-untyped-call]
513+
lambda_function.Code = self._construct_code_dict()
506514
lambda_function.KmsKeyArn = self.KmsKeyArn
507515
lambda_function.ReservedConcurrentExecutions = self.ReservedConcurrentExecutions
508516
lambda_function.Tags = self._construct_tag_list(self.Tags)
@@ -694,7 +702,7 @@ def _validate_dlq(self, dead_letter_queue: Dict[str, Any]) -> None:
694702
self.logical_id, "'DeadLetterQueue' requires Type of {}".format(valid_dlq_types)
695703
)
696704

697-
def _event_resources_to_link(self, resources): # type: ignore[no-untyped-def]
705+
def _event_resources_to_link(self, resources: Dict[str, Any]) -> Dict[str, Any]:
698706
event_resources = {}
699707
if self.Events:
700708
for logical_id, event_dict in self.Events.items():
@@ -708,7 +716,7 @@ def _event_resources_to_link(self, resources): # type: ignore[no-untyped-def]
708716
return event_resources
709717

710718
@staticmethod
711-
def order_events(event): # type: ignore[no-untyped-def]
719+
def order_events(event: Tuple[str, Any]) -> Any:
712720
"""
713721
Helper method for sorting Function Events. Returns a key to use in sorting this event
714722
@@ -722,9 +730,14 @@ def order_events(event): # type: ignore[no-untyped-def]
722730
return logical_id
723731
return event_dict.get("Properties", {}).get("Path", logical_id)
724732

725-
def _generate_event_resources( # type: ignore[no-untyped-def]
726-
self, lambda_function, execution_role, event_resources, intrinsics_resolver, lambda_alias=None
727-
):
733+
def _generate_event_resources(
734+
self,
735+
lambda_function: LambdaFunction,
736+
execution_role: Optional[IAMRole],
737+
event_resources: Any,
738+
intrinsics_resolver: IntrinsicsResolver,
739+
lambda_alias: Optional[LambdaAlias] = None,
740+
) -> List[Any]:
728741
"""Generates and returns the resources associated with this function's events.
729742
730743
:param model.lambda_.LambdaFunction lambda_function: generated Lambda function
@@ -761,7 +774,7 @@ def _generate_event_resources( # type: ignore[no-untyped-def]
761774

762775
return resources
763776

764-
def _construct_code_dict(self): # type: ignore[no-untyped-def]
777+
def _construct_code_dict(self) -> Dict[str, Any]:
765778
"""Constructs Lambda Code Dictionary based on the accepted SAM artifact properties such
766779
as `InlineCode`, `CodeUri` and `ImageUri` and also raises errors if more than one of them is
767780
defined. `PackageType` determines which artifacts are considered.
@@ -782,11 +795,11 @@ def _construct_code_dict(self): # type: ignore[no-untyped-def]
782795

783796
# Inline function for transformation of inline code.
784797
# It accepts arbitrary argumemnts, because the arguments do not matter for the result.
785-
def _construct_inline_code(*args, **kwargs): # type: ignore[no-untyped-def]
798+
def _construct_inline_code(*args: Any, **kwargs: Dict[str, Any]) -> Dict[str, Any]:
786799
return {"ZipFile": self.InlineCode}
787800

788801
# dispatch mechanism per artifact on how it needs to be transformed.
789-
artifact_dispatch = {
802+
artifact_dispatch: Dict[str, Callable[..., Dict[str, Any]]] = {
790803
"InlineCode": _construct_inline_code,
791804
"CodeUri": construct_s3_location_object,
792805
"ImageUri": construct_image_code_object,
@@ -813,8 +826,8 @@ def _construct_inline_code(*args, **kwargs): # type: ignore[no-untyped-def]
813826
filtered_key = "ImageUri"
814827
else:
815828
raise InvalidResourceException(self.logical_id, "Either 'InlineCode' or 'CodeUri' must be set.")
816-
dispatch_function = artifact_dispatch[filtered_key]
817-
return dispatch_function(artifacts[filtered_key], self.logical_id, filtered_key) # type: ignore[operator]
829+
dispatch_function: Callable[..., Dict[str, Any]] = artifact_dispatch[filtered_key]
830+
return dispatch_function(artifacts[filtered_key], self.logical_id, filtered_key)
818831

819832
def _construct_version(
820833
self, function: LambdaFunction, intrinsics_resolver: IntrinsicsResolver, code_sha256: Optional[str] = None
@@ -969,7 +982,7 @@ def _validate_deployment_preference_and_add_update_policy(
969982

970983
def _resolve_property_to_boolean(
971984
self,
972-
property_value: Union[bool, str, dict], # type: ignore[type-arg]
985+
property_value: Union[bool, str, Dict[str, Any]],
973986
property_name: str,
974987
intrinsics_resolver: IntrinsicsResolver,
975988
mappings_resolver: IntrinsicsResolver,
@@ -1557,12 +1570,12 @@ def to_cloudformation(self, **kwargs): # type: ignore[no-untyped-def]
15571570
resources = []
15581571

15591572
# Append any CFN resources:
1560-
intrinsics_resolver = kwargs["intrinsics_resolver"]
1561-
resources.append(self._construct_lambda_layer(intrinsics_resolver)) # type: ignore[no-untyped-call]
1573+
intrinsics_resolver: IntrinsicsResolver = kwargs["intrinsics_resolver"]
1574+
resources.append(self._construct_lambda_layer(intrinsics_resolver))
15621575

15631576
return resources
15641577

1565-
def _construct_lambda_layer(self, intrinsics_resolver): # type: ignore[no-untyped-def]
1578+
def _construct_lambda_layer(self, intrinsics_resolver: IntrinsicsResolver) -> LambdaLayerVersion:
15661579
"""Constructs and returns the Lambda function.
15671580
15681581
:returns: a list containing the Lambda function and execution role resources
@@ -1588,12 +1601,12 @@ def _construct_lambda_layer(self, intrinsics_resolver): # type: ignore[no-untyp
15881601
old_logical_id = self.logical_id
15891602

15901603
# This is to prevent the passthrough resource attributes to be included for hashing
1591-
hash_dict = copy.deepcopy(self.to_dict()) # type: ignore[no-untyped-call]
1592-
if "DeletionPolicy" in hash_dict.get(old_logical_id):
1604+
hash_dict = copy.deepcopy(self.to_dict())
1605+
if "DeletionPolicy" in hash_dict.get(old_logical_id, {}):
15931606
del hash_dict[old_logical_id]["DeletionPolicy"]
1594-
if "UpdateReplacePolicy" in hash_dict.get(old_logical_id):
1607+
if "UpdateReplacePolicy" in hash_dict.get(old_logical_id, {}):
15951608
del hash_dict[old_logical_id]["UpdateReplacePolicy"]
1596-
if "Metadata" in hash_dict.get(old_logical_id):
1609+
if "Metadata" in hash_dict.get(old_logical_id, {}):
15971610
del hash_dict[old_logical_id]["Metadata"]
15981611

15991612
new_logical_id = logical_id_generator.LogicalIdGenerator(old_logical_id, hash_dict).gen()
@@ -1615,10 +1628,10 @@ def _construct_lambda_layer(self, intrinsics_resolver): # type: ignore[no-untyp
16151628

16161629
lambda_layer.LayerName = self.LayerName
16171630
lambda_layer.Description = self.Description
1618-
lambda_layer.Content = construct_s3_location_object(self.ContentUri, self.logical_id, "ContentUri") # type: ignore[no-untyped-call]
1631+
lambda_layer.Content = construct_s3_location_object(self.ContentUri, self.logical_id, "ContentUri")
16191632

16201633
lambda_layer.CompatibleArchitectures = self.CompatibleArchitectures
1621-
self._validate_architectures(lambda_layer) # type: ignore[no-untyped-call]
1634+
self._validate_architectures(lambda_layer)
16221635
lambda_layer.CompatibleRuntimes = self.CompatibleRuntimes
16231636
lambda_layer.LicenseInfo = self.LicenseInfo
16241637

@@ -1658,7 +1671,7 @@ def _get_retention_policy_value(self) -> Optional[str]:
16581671
"'RetentionPolicy' must be one of the following options: {}.".format([self.RETAIN, self.DELETE]),
16591672
)
16601673

1661-
def _validate_architectures(self, lambda_layer): # type: ignore[no-untyped-def]
1674+
def _validate_architectures(self, lambda_layer: LambdaLayerVersion) -> None:
16621675
"""Validate the values inside the CompatibleArchitectures field of a layer
16631676
16641677
Parameters
@@ -1718,7 +1731,7 @@ class SamStateMachine(SamResourceMacro):
17181731
Tracing: Optional[Dict[str, Any]]
17191732
PermissionsBoundary: Optional[Intrinsicable[str]]
17201733

1721-
event_resolver = ResourceTypeResolver( # type: ignore[no-untyped-call]
1734+
event_resolver = ResourceTypeResolver(
17221735
samtranslator.model.stepfunctions.events,
17231736
samtranslator.model.eventsources.scheduler,
17241737
)
@@ -1756,13 +1769,13 @@ def to_cloudformation(self, **kwargs): # type: ignore[no-untyped-def]
17561769
resources = state_machine_generator.to_cloudformation()
17571770
return resources
17581771

1759-
def resources_to_link(self, resources): # type: ignore[no-untyped-def]
1772+
def resources_to_link(self, resources: Dict[str, Any]) -> Dict[str, Any]:
17601773
try:
1761-
return {"event_resources": self._event_resources_to_link(resources)} # type: ignore[no-untyped-call]
1774+
return {"event_resources": self._event_resources_to_link(resources)}
17621775
except InvalidEventException as e:
17631776
raise InvalidResourceException(self.logical_id, e.message)
17641777

1765-
def _event_resources_to_link(self, resources): # type: ignore[no-untyped-def]
1778+
def _event_resources_to_link(self, resources: Dict[str, Any]) -> Dict[str, Any]:
17661779
event_resources = {}
17671780
if self.Events:
17681781
for logical_id, event_dict in self.Events.items():

samtranslator/translator/translator.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -123,7 +123,7 @@ def translate(
123123
self.sam_parser.parse(sam_template=sam_template, parameter_values=parameter_values, sam_plugins=sam_plugins)
124124

125125
template = copy.deepcopy(sam_template)
126-
macro_resolver = ResourceTypeResolver(sam_resources) # type: ignore[no-untyped-call]
126+
macro_resolver = ResourceTypeResolver(sam_resources)
127127
intrinsics_resolver = IntrinsicsResolver(parameter_values)
128128

129129
# ResourceResolver is used by connector, its "resources" will be
@@ -197,7 +197,7 @@ def translate(
197197
for logical_id in deployment_preference_collection.enabled_logical_ids():
198198
try:
199199
template["Resources"].update(
200-
deployment_preference_collection.deployment_group(logical_id).to_dict() # type: ignore[no-untyped-call]
200+
deployment_preference_collection.deployment_group(logical_id).to_dict()
201201
)
202202
except InvalidResourceException as e:
203203
document_errors.append(e) # type: ignore[arg-type]

0 commit comments

Comments
 (0)