Skip to content

chore(ci): enable Ruff rule COM812 and fix the errors #2595

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 27, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 26 additions & 7 deletions aws_lambda_powertools/event_handler/api_gateway.py
Original file line number Diff line number Diff line change
Expand Up @@ -209,7 +209,13 @@ class Route:
"""Internally used Route Configuration"""

def __init__(
self, method: str, rule: Pattern, func: Callable, cors: bool, compress: bool, cache_control: Optional[str]
self,
method: str,
rule: Pattern,
func: Callable,
cors: bool,
compress: bool,
cache_control: Optional[str],
):
self.method = method.upper()
self.rule = rule
Expand Down Expand Up @@ -237,7 +243,9 @@ def _add_cache_control(self, cache_control: str):

@staticmethod
def _has_compression_enabled(
route_compression: bool, response_compression: Optional[bool], event: BaseProxyEvent
route_compression: bool,
response_compression: Optional[bool],
event: BaseProxyEvent,
) -> bool:
"""
Checks if compression is enabled.
Expand Down Expand Up @@ -285,7 +293,9 @@ def _route(self, event: BaseProxyEvent, cors: Optional[CORSConfig]):
if self.route.cache_control:
self._add_cache_control(self.route.cache_control)
if self._has_compression_enabled(
route_compression=self.route.compress, response_compression=self.response.compress, event=event
route_compression=self.route.compress,
response_compression=self.response.compress,
event=event,
):
self._compress()

Expand Down Expand Up @@ -400,7 +410,11 @@ def lambda_handler(event, context):
return self.route(rule, "PUT", cors, compress, cache_control)

def delete(
self, rule: str, cors: Optional[bool] = None, compress: bool = False, cache_control: Optional[str] = None
self,
rule: str,
cors: Optional[bool] = None,
compress: bool = False,
cache_control: Optional[str] = None,
):
"""Delete route decorator with DELETE `method`

Expand All @@ -427,7 +441,11 @@ def lambda_handler(event, context):
return self.route(rule, "DELETE", cors, compress, cache_control)

def patch(
self, rule: str, cors: Optional[bool] = None, compress: bool = False, cache_control: Optional[str] = None
self,
rule: str,
cors: Optional[bool] = None,
compress: bool = False,
cache_control: Optional[str] = None,
):
"""Patch route decorator with PATCH `method`

Expand Down Expand Up @@ -566,7 +584,8 @@ def register_resolver(func: Callable):
route_key = item + rule
if route_key in self._route_keys:
warnings.warn(
f"A route like this was already registered. method: '{item}' rule: '{rule}'", stacklevel=2
f"A route like this was already registered. method: '{item}' rule: '{rule}'",
stacklevel=2,
)
self._route_keys.append(route_key)
if cors_enabled:
Expand Down Expand Up @@ -725,7 +744,7 @@ def _not_found(self, method: str) -> ResponseBuilder:
content_type=content_types.APPLICATION_JSON,
headers=headers,
body=self._json_dump({"statusCode": HTTPStatus.NOT_FOUND.value, "message": "Not found"}),
)
),
)

def _call_route(self, route: Route, args: Dict[str, str]) -> ResponseBuilder:
Expand Down
10 changes: 8 additions & 2 deletions aws_lambda_powertools/event_handler/appsync.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,10 @@ def __init__(self):
self.context = {} # early init as customers might add context before event resolution

def resolve(
self, event: dict, context: LambdaContext, data_model: Type[AppSyncResolverEvent] = AppSyncResolverEvent
self,
event: dict,
context: LambdaContext,
data_model: Type[AppSyncResolverEvent] = AppSyncResolverEvent,
) -> Any:
"""Resolve field_name

Expand Down Expand Up @@ -183,7 +186,10 @@ def _get_resolver(self, type_name: str, field_name: str) -> Callable:
return resolver["func"]

def __call__(
self, event: dict, context: LambdaContext, data_model: Type[AppSyncResolverEvent] = AppSyncResolverEvent
self,
event: dict,
context: LambdaContext,
data_model: Type[AppSyncResolverEvent] = AppSyncResolverEvent,
) -> Any:
"""Implicit lambda handler which internally calls `resolve`"""
return self.resolve(event, context, data_model)
Expand Down
5 changes: 4 additions & 1 deletion aws_lambda_powertools/logging/formatter.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,10 @@ def __init__(
constants.PRETTY_INDENT if powertools_dev_is_set() else constants.COMPACT_INDENT
) # indented json serialization when in AWS SAM Local
self.json_serializer = json_serializer or partial(
json.dumps, default=self.json_default, separators=(",", ":"), indent=self.json_indent
json.dumps,
default=self.json_default,
separators=(",", ":"),
indent=self.json_indent,
)

self.datefmt = datefmt
Expand Down
55 changes: 44 additions & 11 deletions aws_lambda_powertools/logging/logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -223,18 +223,20 @@ def __init__(
**kwargs,
):
self.service = resolve_env_var_choice(
choice=service, env=os.getenv(constants.SERVICE_NAME_ENV, "service_undefined")
choice=service,
env=os.getenv(constants.SERVICE_NAME_ENV, "service_undefined"),
)
self.sampling_rate = resolve_env_var_choice(
choice=sampling_rate, env=os.getenv(constants.LOGGER_LOG_SAMPLING_RATE)
choice=sampling_rate,
env=os.getenv(constants.LOGGER_LOG_SAMPLING_RATE),
)
self.child = child
self.logger_formatter = logger_formatter
self.logger_handler = logger_handler or logging.StreamHandler(stream)
self.log_uncaught_exceptions = log_uncaught_exceptions

self._is_deduplication_disabled = resolve_truthy_env_var_choice(
env=os.getenv(constants.LOGGER_LOG_DEDUPLICATION_ENV, "false")
env=os.getenv(constants.LOGGER_LOG_DEDUPLICATION_ENV, "false"),
)
self._default_log_keys = {"service": self.service, "sampling_rate": self.sampling_rate}
self._logger = self._get_logger()
Expand Down Expand Up @@ -327,7 +329,7 @@ def _configure_sampling(self):
except ValueError:
raise InvalidLoggerSamplingRateError(
f"Expected a float value ranging 0 to 1, but received {self.sampling_rate} instead."
f"Please review POWERTOOLS_LOGGER_SAMPLE_RATE environment variable."
f"Please review POWERTOOLS_LOGGER_SAMPLE_RATE environment variable.",
)

@overload
Expand Down Expand Up @@ -415,7 +417,8 @@ def handler(event, context):
)

log_event = resolve_truthy_env_var_choice(
env=os.getenv(constants.LOGGER_LOG_EVENT_ENV, "false"), choice=log_event
env=os.getenv(constants.LOGGER_LOG_EVENT_ENV, "false"),
choice=log_event,
)

@functools.wraps(lambda_handler)
Expand Down Expand Up @@ -456,7 +459,12 @@ def info(
if sys.version_info < (3, 8): # pragma: no cover
return self._logger.info(msg, *args, exc_info=exc_info, stack_info=stack_info, extra=extra)
return self._logger.info(
msg, *args, exc_info=exc_info, stack_info=stack_info, stacklevel=stacklevel, extra=extra
msg,
*args,
exc_info=exc_info,
stack_info=stack_info,
stacklevel=stacklevel,
extra=extra,
)

def error(
Expand All @@ -476,7 +484,12 @@ def error(
if sys.version_info < (3, 8): # pragma: no cover
return self._logger.error(msg, *args, exc_info=exc_info, stack_info=stack_info, extra=extra)
return self._logger.error(
msg, *args, exc_info=exc_info, stack_info=stack_info, stacklevel=stacklevel, extra=extra
msg,
*args,
exc_info=exc_info,
stack_info=stack_info,
stacklevel=stacklevel,
extra=extra,
)

def exception(
Expand All @@ -496,7 +509,12 @@ def exception(
if sys.version_info < (3, 8): # pragma: no cover
return self._logger.exception(msg, *args, exc_info=exc_info, stack_info=stack_info, extra=extra)
return self._logger.exception(
msg, *args, exc_info=exc_info, stack_info=stack_info, stacklevel=stacklevel, extra=extra
msg,
*args,
exc_info=exc_info,
stack_info=stack_info,
stacklevel=stacklevel,
extra=extra,
)

def critical(
Expand All @@ -516,7 +534,12 @@ def critical(
if sys.version_info < (3, 8): # pragma: no cover
return self._logger.critical(msg, *args, exc_info=exc_info, stack_info=stack_info, extra=extra)
return self._logger.critical(
msg, *args, exc_info=exc_info, stack_info=stack_info, stacklevel=stacklevel, extra=extra
msg,
*args,
exc_info=exc_info,
stack_info=stack_info,
stacklevel=stacklevel,
extra=extra,
)

def warning(
Expand All @@ -536,7 +559,12 @@ def warning(
if sys.version_info < (3, 8): # pragma: no cover
return self._logger.warning(msg, *args, exc_info=exc_info, stack_info=stack_info, extra=extra)
return self._logger.warning(
msg, *args, exc_info=exc_info, stack_info=stack_info, stacklevel=stacklevel, extra=extra
msg,
*args,
exc_info=exc_info,
stack_info=stack_info,
stacklevel=stacklevel,
extra=extra,
)

def debug(
Expand All @@ -556,7 +584,12 @@ def debug(
if sys.version_info < (3, 8): # pragma: no cover
return self._logger.debug(msg, *args, exc_info=exc_info, stack_info=stack_info, extra=extra)
return self._logger.debug(
msg, *args, exc_info=exc_info, stack_info=stack_info, stacklevel=stacklevel, extra=extra
msg,
*args,
exc_info=exc_info,
stack_info=stack_info,
stacklevel=stacklevel,
extra=extra,
)

def append_keys(self, **additional_keys):
Expand Down
4 changes: 3 additions & 1 deletion aws_lambda_powertools/logging/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,9 @@ def _exclude_registered_loggers_filter(loggers: Set[str]) -> List[logging.Logger


def _find_registered_loggers(
source_logger: Logger, loggers: Set[str], filter_func: Callable[[Set[str]], List[logging.Logger]]
source_logger: Logger,
loggers: Set[str],
filter_func: Callable[[Set[str]], List[logging.Logger]],
) -> List[logging.Logger]:
"""Filter root loggers based on provided parameters."""
root_loggers = filter_func(loggers)
Expand Down
13 changes: 8 additions & 5 deletions aws_lambda_powertools/metrics/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,10 @@ def add_metric(
self.metric_set.clear()

def serialize_metric_set(
self, metrics: Optional[Dict] = None, dimensions: Optional[Dict] = None, metadata: Optional[Dict] = None
self,
metrics: Optional[Dict] = None,
dimensions: Optional[Dict] = None,
metadata: Optional[Dict] = None,
) -> Dict:
"""Serializes metric and dimensions set

Expand Down Expand Up @@ -256,7 +259,7 @@ def serialize_metric_set(
"Namespace": self.namespace, # "test_namespace"
"Dimensions": [list(dimensions.keys())], # [ "service" ]
"Metrics": metric_definition,
}
},
],
},
**dimensions, # "service": "test_service"
Expand All @@ -283,7 +286,7 @@ def add_dimension(self, name: str, value: str) -> None:
logger.debug(f"Adding dimension: {name}:{value}")
if len(self.dimension_set) == MAX_DIMENSIONS:
raise SchemaValidationError(
f"Maximum number of dimensions exceeded ({MAX_DIMENSIONS}): Unable to add dimension {name}."
f"Maximum number of dimensions exceeded ({MAX_DIMENSIONS}): Unable to add dimension {name}.",
)
# Cast value to str according to EMF spec
# Majority of values are expected to be string already, so
Expand Down Expand Up @@ -443,7 +446,7 @@ def _extract_metric_resolution_value(self, resolution: Union[int, MetricResoluti
return resolution

raise MetricResolutionError(
f"Invalid metric resolution '{resolution}', expected either option: {self._metric_resolutions}" # noqa: E501
f"Invalid metric resolution '{resolution}', expected either option: {self._metric_resolutions}", # noqa: E501
)

def _extract_metric_unit_value(self, unit: Union[str, MetricUnit]) -> str:
Expand Down Expand Up @@ -471,7 +474,7 @@ def _extract_metric_unit_value(self, unit: Union[str, MetricUnit]) -> str:

if unit not in self._metric_units:
raise MetricUnitError(
f"Invalid metric unit '{unit}', expected either option: {self._metric_unit_valid_options}"
f"Invalid metric unit '{unit}', expected either option: {self._metric_unit_valid_options}",
)

if isinstance(unit, MetricUnit):
Expand Down
5 changes: 3 additions & 2 deletions aws_lambda_powertools/middleware_factory/factory.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,8 @@ def lambda_handler(event, context):
return functools.partial(lambda_handler_decorator, trace_execution=trace_execution)

trace_execution = resolve_truthy_env_var_choice(
env=os.getenv(constants.MIDDLEWARE_FACTORY_TRACE_ENV, "false"), choice=trace_execution
env=os.getenv(constants.MIDDLEWARE_FACTORY_TRACE_ENV, "false"),
choice=trace_execution,
)

@functools.wraps(decorator)
Expand All @@ -119,7 +120,7 @@ def final_decorator(func: Optional[Callable] = None, **kwargs: Any):
if not inspect.isfunction(func):
# @custom_middleware(True) vs @custom_middleware(log_event=True)
raise MiddlewareInvalidArgumentError(
f"Only keyword arguments is supported for middlewares: {decorator.__qualname__} received {func}" # type: ignore # noqa: E501
f"Only keyword arguments is supported for middlewares: {decorator.__qualname__} received {func}", # type: ignore # noqa: E501
)

@functools.wraps(func)
Expand Down
6 changes: 4 additions & 2 deletions aws_lambda_powertools/shared/functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,8 @@ def resolve_env_var_choice(env: Optional[str], choice: Optional[str]) -> str:


def resolve_env_var_choice(
env: Optional[str] = None, choice: Optional[Union[str, float]] = None
env: Optional[str] = None,
choice: Optional[Union[str, float]] = None,
) -> Optional[Union[str, float]]:
"""Pick explicit choice over env, if available, otherwise return env value received

Expand Down Expand Up @@ -112,7 +113,8 @@ def powertools_dev_is_set() -> bool:
is_on = strtobool(os.getenv(constants.POWERTOOLS_DEV_ENV, "0"))
if is_on:
warnings.warn(
"POWERTOOLS_DEV environment variable is enabled. Increasing verbosity across utilities.", stacklevel=2
"POWERTOOLS_DEV environment variable is enabled. Increasing verbosity across utilities.",
stacklevel=2,
)
return True

Expand Down
Loading