Skip to content

refactor(general): add support for ruff format #6512

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 3 commits into from
Apr 17, 2025
Merged
Show file tree
Hide file tree
Changes from 2 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
2 changes: 2 additions & 0 deletions .github/workflows/quality_check.yml
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,8 @@ jobs:
run: make dev-quality-code
- name: Checking third-party library licenses
run: make check-licenses
- name: Checking and enforcing format
run: make format-check
- name: Formatting and Linting
run: make lint
- name: Static type checking
Expand Down
8 changes: 4 additions & 4 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,13 @@ repos:
- id: check-toml
- repo: local
hooks:
- id: black
name: formatting::black
entry: poetry run black
- id: ruff
name: formatting::ruff
entry: poetry run ruff format
language: system
types: [python]
- id: ruff
name: linting-format::ruff
name: linting::ruff
entry: poetry run ruff check
language: system
types: [python]
Expand Down
5 changes: 4 additions & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,11 @@ dev-gitpod:
check-licenses:
poetry run licensecheck -u poetry:dev

format-check:
poetry run ruff format aws_lambda_powertools tests examples --check

format:
poetry run black aws_lambda_powertools tests examples
poetry run ruff format aws_lambda_powertools tests examples

lint: format
poetry run ruff check aws_lambda_powertools tests examples
Expand Down
2 changes: 0 additions & 2 deletions aws_lambda_powertools/event_handler/api_gateway.py
Original file line number Diff line number Diff line change
Expand Up @@ -1604,7 +1604,6 @@ def _validate_response_validation_error_http_code(
response_validation_error_http_code: HTTPStatus | int | None,
enable_validation: bool,
) -> HTTPStatus:

if response_validation_error_http_code and not enable_validation:
msg = "'response_validation_error_http_code' cannot be set when enable_validation is False."
raise ValueError(msg)
Expand All @@ -1613,7 +1612,6 @@ def _validate_response_validation_error_http_code(
not isinstance(response_validation_error_http_code, HTTPStatus)
and response_validation_error_http_code is not None
):

try:
response_validation_error_http_code = HTTPStatus(response_validation_error_http_code)
except ValueError:
Expand Down
1 change: 0 additions & 1 deletion aws_lambda_powertools/event_handler/openapi/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,6 @@ class OpenAPIExtensions(BaseModel):
@model_validator(mode="before")
def serialize_openapi_extension_v2(self):
if isinstance(self, dict) and self.get("openapi_extensions"):

openapi_extension_value = self.get("openapi_extensions")

for extension_key in openapi_extension_value:
Expand Down
1 change: 0 additions & 1 deletion aws_lambda_powertools/logging/logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -242,7 +242,6 @@ def __init__(
buffer_config: LoggerBufferConfig | None = None,
**kwargs,
) -> None:

# Used in case of sampling
self.initial_log_level = self._determine_log_level(level)

Expand Down
3 changes: 1 addition & 2 deletions aws_lambda_powertools/utilities/batch/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -296,8 +296,7 @@ def _clean(self):

if self._entire_batch_failed() and self.raise_on_entire_batch_failure:
raise BatchProcessingError(
msg=f"All records failed processing. {len(self.exceptions)} individual errors logged "
f"separately below.",
msg=f"All records failed processing. {len(self.exceptions)} individual errors logged separately below.",
child_exceptions=self.exceptions,
)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -314,7 +314,6 @@ def put_artifact(self, artifact_name: str, body: Any, content_type: str) -> None
# So we are using if/else instead.

if self.data.encryption_key:

encryption_key_id = self.data.encryption_key.get_id
encryption_key_type = self.data.encryption_key.get_type
if encryption_key_type == "KMS":
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,6 @@ def source_ip(self) -> str:


class TransferFamilyAuthorizerResponse:

def _build_authentication_response(
self,
role_arn: str,
Expand All @@ -51,7 +50,6 @@ def _build_authentication_response(
user_uid: int | None = None,
public_keys: str | None = None,
) -> dict[str, Any]:

response: dict[str, Any] = {}

if home_directory_type == "PATH":
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,6 @@ def erase(
masking_rules: dict | None = None,
**kwargs,
) -> Any:

result: Any = DATA_MASKING_STRING

if not any([dynamic_mask, custom_mask, regex_pattern, mask_format, masking_rules]):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,6 @@ def from_dict(self, data: dict) -> DataClass:

@classmethod
def instantiate(cls, model_type: Any) -> BaseIdempotencySerializer:

model_type = get_actual_type(model_type=model_type)

if model_type is None:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,6 @@ def from_dict(self, data: dict) -> BaseModel:

@classmethod
def instantiate(cls, model_type: Any) -> BaseIdempotencySerializer:

model_type = get_actual_type(model_type=model_type)

if model_type is None:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,7 @@
logger = Logger()


class InvalidPayload(Exception):
...
class InvalidPayload(Exception): ...


@tracer.capture_method
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@
local_cache_capacity=200,
max_cache_age_seconds=400,
max_messages_encrypted=200,
max_bytes_encrypted=2000)
max_bytes_encrypted=2000,
)

data_masker = DataMasking(provider=encryption_provider)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@


class AgentsCdkStack(Stack):

def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
super().__init__(scope, construct_id, **kwargs)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,7 @@
}


class PostRelatedNotFound(Exception):
...
class PostRelatedNotFound(Exception): ...


@app.batch_resolver(type_name="Query", field_name="relatedPosts", raise_on_error=True) # (1)!
Expand Down
1 change: 1 addition & 0 deletions examples/event_handler_rest/src/raising_http_errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ def service_error():
def service_unavailable_error():
raise ServiceUnavailableError("Service is temporarily unavailable") # HTTP 503


@app.get("/todos")
@tracer.capture_method
def get_todos():
Expand Down
2 changes: 1 addition & 1 deletion examples/event_sources/src/cloudWatchDashboard.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,6 @@ def lambda_handler(event: CloudWatchDashboardCustomWidgetEvent, context):
"markdown": f"""
Dashboard: {event.widget_context.dashboard_name}
Time Range: {time_range.start} to {time_range.end}
Theme: {event.widget_context.theme or 'default'}
Theme: {event.widget_context.theme or "default"}
""",
}
3 changes: 1 addition & 2 deletions examples/event_sources/src/s3_batch_operation.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,5 +33,4 @@ def lambda_handler(event: S3BatchOperationEvent, context: LambdaContext):
return response.asdict()


def do_some_work(s3_client, src_bucket: str, src_key: str):
...
def do_some_work(s3_client, src_bucket: str, src_key: str): ...
1 change: 0 additions & 1 deletion examples/homepage/install/arm64/cdk_arm64.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@


class SampleApp(Stack):

def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
super().__init__(scope, construct_id, **kwargs)

Expand Down
1 change: 0 additions & 1 deletion examples/homepage/install/sar/cdk_sar.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@


class SampleApp(Stack):

def __init__(self, scope: Construct, id_: str) -> None:
super().__init__(scope, id_)

Expand Down
1 change: 0 additions & 1 deletion examples/homepage/install/x86_64/cdk_x86.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@


class SampleApp(Stack):

def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
super().__init__(scope, construct_id, **kwargs)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ class Payment:
class PaymentError(Exception): ...


@idempotent(persistence_store=persistence_layer, key_prefix="my_custom_prefix") # (1)!
@idempotent(persistence_store=persistence_layer, key_prefix="my_custom_prefix") # (1)!
def lambda_handler(event: dict, context: LambdaContext):
try:
payment: Payment = create_subscription_payment(event)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,15 +29,15 @@ class Order:
data_keyword_argument="order",
config=config,
persistence_store=dynamodb,
key_prefix="my_custom_prefix", # (1)!
key_prefix="my_custom_prefix", # (1)!
)
def process_order(order: Order):
def process_order(order: Order):
return f"processed order {order.order_id}"


def lambda_handler(event: dict, context: LambdaContext):
# see Lambda timeouts section
config.register_lambda_context(context)
config.register_lambda_context(context)

order_item = OrderItem(sku="fake", description="sample")
order = Order(item=order_item, order_id=1)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,7 @@
config = IdempotencyConfig(event_key_jmespath="powertools_json(body)")


class PaymentError(Exception):
...
class PaymentError(Exception): ...


@idempotent(config=config, persistence_store=persistence_layer)
Expand Down
3 changes: 1 addition & 2 deletions examples/logger/src/append_keys_vs_extra.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,7 @@
logger = Logger(service="payment")


class PaymentError(Exception):
...
class PaymentError(Exception): ...


def lambda_handler(event, context):
Expand Down
3 changes: 1 addition & 2 deletions examples/metrics/src/capture_cold_start_metric.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,4 @@


@metrics.log_metrics(capture_cold_start_metric=True)
def lambda_handler(event: dict, context: LambdaContext):
...
def lambda_handler(event: dict, context: LambdaContext): ...
2 changes: 1 addition & 1 deletion examples/metrics/src/flush_metrics.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
metrics = Metrics()


def book_flight(flight_id: str, **kwargs):
def book_flight(flight_id: str, **kwargs):
# logic to book flight
...
metrics.add_metric(name="SuccessfulBooking", unit=MetricUnit.Count, value=1)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,7 @@


def lambda_handler(event: dict, context: LambdaContext):

for record in event:

record_id: str = record.get("record_id")
amount: int = record.get("amount")
timestamp: int = record.get("timestamp")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@


def lambda_handler(event: dict, context: LambdaContext):

try:
# Usually an endpoint is not sensitive data, so we store it in DynamoDB Table
endpoint_comments: Any = dynamodb_provider.get("comments_endpoint")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,13 @@


def lambda_handler(event: dict, context: LambdaContext):

try:
# Retrieve multiple parameters using HASH KEY
all_parameters: Any = dynamodb_provider.get_multiple("config")
endpoint_comments = "https://jsonplaceholder.typicode.com/noexists/"
limit = 2

for parameter, value in all_parameters.items():

if parameter == "endpoint_comments":
endpoint_comments = value

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@


def lambda_handler(event: dict, context: LambdaContext):

try:
# Usually an endpoint is not sensitive data, so we store it in DynamoDB Table
endpoint_comments: Any = dynamodb_provider.get("comments_endpoint")
Expand Down
1 change: 0 additions & 1 deletion examples/parameters/src/builtin_provider_secret.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@


def lambda_handler(event: dict, context: LambdaContext):

try:
# Usually an endpoint is not sensitive data, so we store it in SSM Parameters
endpoint_comments: Any = parameters.get_parameter("/lambda-powertools/endpoint_comments")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,7 @@
ssm_provider = parameters.SSMProvider()


class ConfigNotFound(Exception):
...
class ConfigNotFound(Exception): ...


def lambda_handler(event: dict, context: LambdaContext):
Expand All @@ -22,7 +21,6 @@ def lambda_handler(event: dict, context: LambdaContext):
endpoint_comments = "https://jsonplaceholder.typicode.com/comments/"

for parameter, value in all_parameters.items():

# query parameter is used to query endpoint
if "query" in parameter:
endpoint_comments = f"{endpoint_comments}{value}"
Expand Down
1 change: 0 additions & 1 deletion examples/parameters/src/getting_started_secret.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@


def lambda_handler(event: dict, context: LambdaContext):

try:
# Usually an endpoint is not sensitive data, so we store it in SSM Parameters
endpoint_comments: Any = parameters.get_parameter("/lambda-powertools/endpoint_comments")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ def lambda_handler(event: dict, context: LambdaContext):
endpoint_comments = "https://jsonplaceholder.typicode.com/noexists/"

for parameter, value in all_parameters.items():

if parameter == "endpoint_comments":
endpoint_comments = value

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ def lambda_handler(event: dict, context: LambdaContext):
endpoint_comments = "https://jsonplaceholder.typicode.com/noexists/"

for parameter, value in all_parameters.items():

if parameter == "endpoint_comments":
endpoint_comments = value

Expand Down
1 change: 0 additions & 1 deletion examples/parameters/src/secret_force_fetch.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@


def lambda_handler(event: dict, context: LambdaContext):

try:
# Usually an endpoint is not sensitive data, so we store it in SSM Parameters
endpoint_comments: Any = parameters.get_parameter("/lambda-powertools/endpoint_comments")
Expand Down
1 change: 0 additions & 1 deletion examples/parameters/src/secret_with_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@


def lambda_handler(event: dict, context: LambdaContext):

try:
# Usually an endpoint is not sensitive data, so we store it in SSM Parameters
endpoint_comments: Any = parameters.get_parameter("/lambda-powertools/endpoint_comments")
Expand Down
1 change: 0 additions & 1 deletion examples/parameters/src/working_with_own_provider_s3.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@


def lambda_handler(event: dict, context: LambdaContext):

try:
# Retrieve a single parameter using key
endpoint_comments: Any = s3_provider.get("comments_endpoint")
Expand Down
Loading
Loading