Skip to content

Commit e7cb90b

Browse files
committed
Replace string formatting with f strings.
1 parent d812fb6 commit e7cb90b

File tree

10 files changed

+31
-43
lines changed

10 files changed

+31
-43
lines changed

datadog_lambda/cold_start.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -50,12 +50,12 @@ def is_new_sandbox():
5050

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

5555

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

6060

6161
class ImportNode(object):

datadog_lambda/handler.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ class HandlerError(Exception):
2222
)
2323
parts = path.rsplit(".", 1)
2424
if len(parts) != 2:
25-
raise HandlerError("Value %s for DD_LAMBDA_HANDLER has invalid format." % path)
25+
raise HandlerError(f"Value {path} for DD_LAMBDA_HANDLER has invalid format.")
2626

2727

2828
(mod_name, handler_name) = parts

datadog_lambda/tag_object.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -30,17 +30,17 @@ def tag_object(span, key, obj, depth=0):
3030
return span.set_tag(key, str(obj))
3131
if isinstance(obj, list):
3232
for k, v in enumerate(obj):
33-
formatted_key = "{}.{}".format(key, k)
33+
formatted_key = f"{key}.{k}"
3434
tag_object(span, formatted_key, v, depth)
3535
return
3636
if hasattr(obj, "items"):
3737
for k, v in obj.items():
38-
formatted_key = "{}.{}".format(key, k)
38+
formatted_key = f"{key}.{k}"
3939
tag_object(span, formatted_key, v, depth)
4040
return
4141
if hasattr(obj, "to_dict"):
4242
for k, v in obj.to_dict().items():
43-
formatted_key = "{}.{}".format(key, k)
43+
formatted_key = f"{key}.{k}"
4444
tag_object(span, formatted_key, v, depth)
4545
return
4646
try:

datadog_lambda/tags.py

Lines changed: 12 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,5 @@
11
import sys
22

3-
from platform import python_version_tuple
4-
53
from datadog_lambda import __version__
64
from datadog_lambda.cold_start import get_cold_start_tag
75

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

1614

1715
def tag_dd_lambda_layer(tags):
@@ -44,9 +42,9 @@ def parse_lambda_tags_from_arn(lambda_context):
4442

4543
# Add the standard tags to a list
4644
tags = [
47-
"region:{}".format(region),
48-
"account_id:{}".format(account_id),
49-
"functionname:{}".format(function_name),
45+
f"region:{region}",
46+
f"account_id:{account_id}",
47+
f"functionname:{function_name}",
5048
]
5149

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

6664
tags.append(resource)
6765

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

7169
def get_runtime_tag():
7270
"""Get the runtime tag from the current Python version"""
73-
major_version, minor_version, _ = python_version_tuple()
74-
75-
return "runtime:python{major}.{minor}".format(
76-
major=major_version, minor=minor_version
77-
)
71+
major, minor = sys.version_info[0], sys.version_info[1]
72+
return f"runtime:python{major}.{minor}"
7873

7974

8075
def get_library_version_tag():
8176
"""Get datadog lambda library tag"""
82-
return "datadog_lambda:v{}".format(__version__)
77+
return f"datadog_lambda:v{__version__}"
8378

8479

8580
def get_enhanced_metrics_tags(lambda_context):
8681
"""Get the list of tags to apply to enhanced metrics"""
8782
return parse_lambda_tags_from_arn(lambda_context) + [
8883
get_cold_start_tag(),
89-
"memorysize:{}".format(lambda_context.memory_limit_in_mb),
84+
f"memorysize:{lambda_context.memory_limit_in_mb}",
9085
get_runtime_tag(),
9186
get_library_version_tag(),
9287
]

datadog_lambda/tracing.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -734,7 +734,7 @@ def create_inferred_span_from_lambda_function_url_event(event, context):
734734
service_name = determine_service_name(service_mapping, api_id, "lambda_url", domain)
735735
method = request_context.get("http", {}).get("method")
736736
path = request_context.get("http", {}).get("path")
737-
resource = "{0} {1}".format(method, path)
737+
resource = f"{method} {path}"
738738
tags = {
739739
"operation_name": "aws.lambda.url",
740740
"http.url": domain + path,
@@ -894,7 +894,7 @@ def create_inferred_span_from_api_gateway_event(
894894
method = event.get("httpMethod")
895895
path = event.get("path")
896896
resource_path = _get_resource_path(event, request_context)
897-
resource = "{0} {1}".format(method, resource_path)
897+
resource = f"{method} {resource_path}"
898898
tags = {
899899
"operation_name": "aws.apigateway.rest",
900900
"http.url": domain + path,
@@ -959,7 +959,7 @@ def create_inferred_span_from_http_api_event(
959959
method = request_context.get("http", {}).get("method")
960960
path = event.get("rawPath")
961961
resource_path = _get_resource_path(event, request_context)
962-
resource = "{0} {1}".format(method, resource_path)
962+
resource = f"{method} {resource_path}"
963963
tags = {
964964
"operation_name": "aws.httpapi",
965965
"endpoint": path,

datadog_lambda/trigger.py

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -204,9 +204,7 @@ def parse_event_source_arn(source: _EventSource, event: dict, context: Any) -> s
204204
distribution_id = (
205205
event_record.get("cf", {}).get("config", {}).get("distributionId")
206206
)
207-
return "arn:{}:cloudfront::{}:distribution/{}".format(
208-
aws_arn, account_id, distribution_id
209-
)
207+
return f"arn:{aws_arn}:cloudfront::{account_id}:distribution/{distribution_id}"
210208

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

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

247243
# e.g. arn:aws:events:us-east-1:123456789012:rule/my-schedule
248244
if source.event_type == EventTypes.CLOUDWATCH_EVENTS and event.get("resources"):

datadog_lambda/wrapper.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -381,9 +381,8 @@ def _after(self, event, context):
381381

382382

383383
def format_err_with_traceback(e):
384-
return "Error {}. Traceback: {}".format(
385-
e, traceback.format_exc().replace("\n", "\r")
386-
)
384+
tb = traceback.format_exc().replace("\n", "\r")
385+
return f"Error {e}. Traceback: {tb}"
387386

388387

389388
datadog_lambda_wrapper = _LambdaDecorator

datadog_lambda/xray.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ def send(host_port_tuple, payload):
4141
def build_segment_payload(payload):
4242
if payload is None:
4343
return None
44-
return '{"format": "json", "version": 1}' + "\n" + payload
44+
return '{"format": "json", "version": 1}\n' + payload
4545

4646

4747
def parse_xray_header(raw_trace_id):

tests/test_tags.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ def get_mock_context(
1818

1919
class TestMetricTags(unittest.TestCase):
2020
def setUp(self):
21-
patcher = patch("datadog_lambda.tags.python_version_tuple")
21+
patcher = patch("sys.version_info", (3, 12, 0))
2222
self.mock_python_version_tuple = patcher.start()
2323
self.addCleanup(patcher.stop)
2424

@@ -65,5 +65,4 @@ def test_parse_lambda_tags_from_arn_alias(self):
6565
)
6666

6767
def test_get_runtime_tag(self):
68-
self.mock_python_version_tuple.return_value = ("3", "12", "0")
6968
self.assertEqual(get_runtime_tag(), "runtime:python3.12")

tests/test_wrapper.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -66,9 +66,8 @@ def setUp(self):
6666
self.mock_is_cold_start.return_value = True
6767
self.addCleanup(patcher.stop)
6868

69-
patcher = patch("datadog_lambda.tags.python_version_tuple")
69+
patcher = patch("sys.version_info", (3, 9, 10))
7070
self.mock_python_version_tuple = patcher.start()
71-
self.mock_python_version_tuple.return_value = ("3", "9", "10")
7271
self.addCleanup(patcher.stop)
7372

7473
patcher = patch("datadog_lambda.metric.write_metric_point_to_stdout")

0 commit comments

Comments
 (0)