Skip to content

Replace string formatting with f strings. #458

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 1, 2024
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
8 changes: 6 additions & 2 deletions datadog_lambda/cold_start.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,12 +50,16 @@ def is_new_sandbox():

def get_cold_start_tag():
"""Returns the cold start tag to be used in metrics"""
return "cold_start:{}".format(str(is_cold_start()).lower())
return "cold_start:true" if _cold_start else "cold_start:false"


def get_proactive_init_tag():
"""Returns the proactive init tag to be used in metrics"""
return "proactive_initialization:{}".format(str(is_proactive_init()).lower())
return (
"proactive_initialization:true"
if _proactive_initialization
else "proactive_initialization:false"
)


class ImportNode(object):
Expand Down
2 changes: 1 addition & 1 deletion datadog_lambda/handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ class HandlerError(Exception):
)
parts = path.rsplit(".", 1)
if len(parts) != 2:
raise HandlerError("Value %s for DD_LAMBDA_HANDLER has invalid format." % path)
raise HandlerError(f"Value {path} for DD_LAMBDA_HANDLER has invalid format.")


(mod_name, handler_name) = parts
Expand Down
6 changes: 3 additions & 3 deletions datadog_lambda/tag_object.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,17 +30,17 @@ def tag_object(span, key, obj, depth=0):
return span.set_tag(key, str(obj))
if isinstance(obj, list):
for k, v in enumerate(obj):
formatted_key = "{}.{}".format(key, k)
formatted_key = f"{key}.{k}"
tag_object(span, formatted_key, v, depth)
return
if hasattr(obj, "items"):
for k, v in obj.items():
formatted_key = "{}.{}".format(key, k)
formatted_key = f"{key}.{k}"
tag_object(span, formatted_key, v, depth)
return
if hasattr(obj, "to_dict"):
for k, v in obj.to_dict().items():
formatted_key = "{}.{}".format(key, k)
formatted_key = f"{key}.{k}"
tag_object(span, formatted_key, v, depth)
return
try:
Expand Down
29 changes: 12 additions & 17 deletions datadog_lambda/tags.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
import sys

from platform import python_version_tuple

from datadog_lambda import __version__
from datadog_lambda.cold_start import get_cold_start_tag

Expand All @@ -10,8 +8,8 @@ def _format_dd_lambda_layer_tag():
"""
Formats the dd_lambda_layer tag, e.g., 'dd_lambda_layer:datadog-python39_1'
"""
runtime = "python{}{}".format(sys.version_info[0], sys.version_info[1])
return "dd_lambda_layer:datadog-{}_{}".format(runtime, __version__)
major, minor = sys.version_info[0], sys.version_info[1]
return f"dd_lambda_layer:datadog-python{major}{minor}_{__version__}"


def tag_dd_lambda_layer(tags):
Expand Down Expand Up @@ -44,9 +42,9 @@ def parse_lambda_tags_from_arn(lambda_context):

# Add the standard tags to a list
tags = [
"region:{}".format(region),
"account_id:{}".format(account_id),
"functionname:{}".format(function_name),
f"region:{region}",
f"account_id:{account_id}",
f"functionname:{function_name}",
]

# Check if we have a version or alias
Expand All @@ -56,12 +54,12 @@ def parse_lambda_tags_from_arn(lambda_context):
alias = alias[1:]
# Versions are numeric. Aliases need the executed version tag
elif not check_if_number(alias):
tags.append("executedversion:{}".format(lambda_context.function_version))
tags.append(f"executedversion:{lambda_context.function_version}")
# create resource tag with function name and alias/version
resource = "resource:{}:{}".format(function_name, alias)
resource = f"resource:{function_name}:{alias}"
else:
# Resource is only the function name otherwise
resource = "resource:{}".format(function_name)
resource = f"resource:{function_name}"

tags.append(resource)

Expand All @@ -70,23 +68,20 @@ def parse_lambda_tags_from_arn(lambda_context):

def get_runtime_tag():
"""Get the runtime tag from the current Python version"""
major_version, minor_version, _ = python_version_tuple()

return "runtime:python{major}.{minor}".format(
major=major_version, minor=minor_version
)
major, minor = sys.version_info[0], sys.version_info[1]
return f"runtime:python{major}.{minor}"


def get_library_version_tag():
"""Get datadog lambda library tag"""
return "datadog_lambda:v{}".format(__version__)
return f"datadog_lambda:v{__version__}"


def get_enhanced_metrics_tags(lambda_context):
"""Get the list of tags to apply to enhanced metrics"""
return parse_lambda_tags_from_arn(lambda_context) + [
get_cold_start_tag(),
"memorysize:{}".format(lambda_context.memory_limit_in_mb),
f"memorysize:{lambda_context.memory_limit_in_mb}",
get_runtime_tag(),
get_library_version_tag(),
]
Expand Down
6 changes: 3 additions & 3 deletions datadog_lambda/tracing.py
Original file line number Diff line number Diff line change
Expand Up @@ -734,7 +734,7 @@ def create_inferred_span_from_lambda_function_url_event(event, context):
service_name = determine_service_name(service_mapping, api_id, "lambda_url", domain)
method = request_context.get("http", {}).get("method")
path = request_context.get("http", {}).get("path")
resource = "{0} {1}".format(method, path)
resource = f"{method} {path}"
tags = {
"operation_name": "aws.lambda.url",
"http.url": domain + path,
Expand Down Expand Up @@ -894,7 +894,7 @@ def create_inferred_span_from_api_gateway_event(
method = event.get("httpMethod")
path = event.get("path")
resource_path = _get_resource_path(event, request_context)
resource = "{0} {1}".format(method, resource_path)
resource = f"{method} {resource_path}"
tags = {
"operation_name": "aws.apigateway.rest",
"http.url": domain + path,
Expand Down Expand Up @@ -959,7 +959,7 @@ def create_inferred_span_from_http_api_event(
method = request_context.get("http", {}).get("method")
path = event.get("rawPath")
resource_path = _get_resource_path(event, request_context)
resource = "{0} {1}".format(method, resource_path)
resource = f"{method} {resource_path}"
tags = {
"operation_name": "aws.httpapi",
"endpoint": path,
Expand Down
14 changes: 5 additions & 9 deletions datadog_lambda/trigger.py
Original file line number Diff line number Diff line change
Expand Up @@ -204,9 +204,7 @@ def parse_event_source_arn(source: _EventSource, event: dict, context: Any) -> s
distribution_id = (
event_record.get("cf", {}).get("config", {}).get("distributionId")
)
return "arn:{}:cloudfront::{}:distribution/{}".format(
aws_arn, account_id, distribution_id
)
return f"arn:{aws_arn}:cloudfront::{account_id}:distribution/{distribution_id}"

# e.g. arn:aws:lambda:<region>:<account_id>:url:<function-name>:<function-qualifier>
if source.equals(EventTypes.LAMBDA_FUNCTION_URL):
Expand All @@ -223,9 +221,9 @@ def parse_event_source_arn(source: _EventSource, event: dict, context: Any) -> s
# e.g. arn:aws:apigateway:us-east-1::/restapis/xyz123/stages/default
if source.event_type == EventTypes.API_GATEWAY:
request_context = event.get("requestContext")
return "arn:{}:apigateway:{}::/restapis/{}/stages/{}".format(
aws_arn, region, request_context.get("apiId"), request_context.get("stage")
)
api_id = request_context.get("apiId")
stage = request_context.get("stage")
return f"arn:{aws_arn}:apigateway:{region}::/restapis/{api_id}/stages/{stage}"

# e.g. arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/lambda-xyz/123
if source.event_type == EventTypes.ALB:
Expand All @@ -240,9 +238,7 @@ def parse_event_source_arn(source: _EventSource, event: dict, context: Any) -> s
data = b"".join(BufferedReader(decompress_stream))
logs = json.loads(data)
log_group = logs.get("logGroup", "cloudwatch")
return "arn:{}:logs:{}:{}:log-group:{}".format(
aws_arn, region, account_id, log_group
)
return f"arn:{aws_arn}:logs:{region}:{account_id}:log-group:{log_group}"

# e.g. arn:aws:events:us-east-1:123456789012:rule/my-schedule
if source.event_type == EventTypes.CLOUDWATCH_EVENTS and event.get("resources"):
Expand Down
5 changes: 2 additions & 3 deletions datadog_lambda/wrapper.py
Original file line number Diff line number Diff line change
Expand Up @@ -381,9 +381,8 @@ def _after(self, event, context):


def format_err_with_traceback(e):
return "Error {}. Traceback: {}".format(
e, traceback.format_exc().replace("\n", "\r")
)
tb = traceback.format_exc().replace("\n", "\r")
return f"Error {e}. Traceback: {tb}"


datadog_lambda_wrapper = _LambdaDecorator
2 changes: 1 addition & 1 deletion datadog_lambda/xray.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ def send(host_port_tuple, payload):
def build_segment_payload(payload):
if payload is None:
return None
return '{"format": "json", "version": 1}' + "\n" + payload
return '{"format": "json", "version": 1}\n' + payload


def parse_xray_header(raw_trace_id):
Expand Down
3 changes: 1 addition & 2 deletions tests/test_tags.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ def get_mock_context(

class TestMetricTags(unittest.TestCase):
def setUp(self):
patcher = patch("datadog_lambda.tags.python_version_tuple")
patcher = patch("sys.version_info", (3, 12, 0))
self.mock_python_version_tuple = patcher.start()
self.addCleanup(patcher.stop)

Expand Down Expand Up @@ -65,5 +65,4 @@ def test_parse_lambda_tags_from_arn_alias(self):
)

def test_get_runtime_tag(self):
self.mock_python_version_tuple.return_value = ("3", "12", "0")
self.assertEqual(get_runtime_tag(), "runtime:python3.12")
11 changes: 5 additions & 6 deletions tests/test_wrapper.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,14 +61,13 @@ def setUp(self):
self.mock_patch_all = patcher.start()
self.addCleanup(patcher.stop)

patcher = patch("datadog_lambda.cold_start.is_cold_start")
self.mock_is_cold_start = patcher.start()
self.mock_is_cold_start.return_value = True
patcher = patch("datadog_lambda.tags.get_cold_start_tag")
self.mock_get_cold_start_tag = patcher.start()
self.mock_get_cold_start_tag.return_value = "cold_start:true"
self.addCleanup(patcher.stop)

patcher = patch("datadog_lambda.tags.python_version_tuple")
patcher = patch("sys.version_info", (3, 9, 10))
self.mock_python_version_tuple = patcher.start()
self.mock_python_version_tuple.return_value = ("3", "9", "10")
self.addCleanup(patcher.stop)

patcher = patch("datadog_lambda.metric.write_metric_point_to_stdout")
Expand Down Expand Up @@ -354,7 +353,7 @@ def lambda_handler(event, context):

lambda_handler(lambda_event, get_mock_context())

self.mock_is_cold_start.return_value = False
self.mock_get_cold_start_tag.return_value = "cold_start:false"

lambda_handler(
lambda_event, get_mock_context(aws_request_id="second-request-id")
Expand Down