Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit d20f4b3

Browse files
adamantikeowais
andauthored
Refactor code using pyupgrade for Python 3.6 (open-telemetry#2238)
* Refactor code using pyupgrade for Python 3.6 This diff is the result of applying the following command to the project: ```shell find . -type f -name "*.py" -exec pyupgrade --py36-plus '{}' + ``` * Revert changes in autogenerated files * Remove changes on autogenerated files Co-authored-by: Owais Lone <[email protected]>
1 parent 64e884a commit d20f4b3

File tree

38 files changed

+38
-86
lines changed

38 files changed

+38
-86
lines changed

docs/examples/basic_context/implicit_context.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,5 +21,5 @@
2121
with tracer.start_span(name="root span") as root_span:
2222
ctx = baggage.set_baggage("foo", "bar")
2323

24-
print("Global context baggage: {}".format(baggage.get_all()))
25-
print("Span context baggage: {}".format(baggage.get_all(context=ctx)))
24+
print(f"Global context baggage: {baggage.get_all()}")
25+
print(f"Span context baggage: {baggage.get_all(context=ctx)}")

docs/examples/datadog_exporter/server.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ def server_request():
5656
with tracer.start_as_current_span("server-inner"):
5757
if param == "error":
5858
raise ValueError("forced server error")
59-
return "served: {}".format(param)
59+
return f"served: {param}"
6060

6161

6262
if __name__ == "__main__":

docs/examples/fork-process-model/flask-gunicorn/app.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ def fibonacci():
5252
fast_span.set_attribute("n", n)
5353
fast_span.set_attribute("nth_fibonacci", ans)
5454

55-
return "F({}) is: ({})".format(n, ans)
55+
return f"F({n}) is: ({ans})"
5656

5757

5858
if __name__ == "__main__":

docs/examples/fork-process-model/flask-uwsgi/app.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,7 @@ def fibonacci():
7272
fast_span.set_attribute("n", n)
7373
fast_span.set_attribute("nth_fibonacci", ans)
7474

75-
return "F({}) is: ({})".format(n, ans)
75+
return f"F({n}) is: ({ans})"
7676

7777

7878
if __name__ == "__main__":

docs/examples/opentracing/rediscache.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ def inner(*args, **kwargs):
4545

4646
scope1.span.log_kv({"msg": "Cache miss, calling function"})
4747
with self.tracer.start_active_span(
48-
'Call "{}"'.format(func.__name__)
48+
f'Call "{func.__name__}"'
4949
) as scope2:
5050
scope2.span.set_tag("func", func.__name__)
5151
scope2.span.set_tag("args", str(args))

docs/getting_started/tests/test_flask.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@
2525
class TestFlask(unittest.TestCase):
2626
def test_flask(self):
2727
dirpath = os.path.dirname(os.path.realpath(__file__))
28-
server_script = "{}/../flask_example.py".format(dirpath)
28+
server_script = f"{dirpath}/../flask_example.py"
2929
server = subprocess.Popen(
3030
[sys.executable, server_script],
3131
stdout=subprocess.PIPE,

docs/getting_started/tests/test_tracing.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020
class TestBasicTracerExample(unittest.TestCase):
2121
def test_basic_tracer(self):
2222
dirpath = os.path.dirname(os.path.realpath(__file__))
23-
test_script = "{}/../tracing_example.py".format(dirpath)
23+
test_script = f"{dirpath}/../tracing_example.py"
2424
output = subprocess.check_output(
2525
(sys.executable, test_script)
2626
).decode()

exporter/opentelemetry-exporter-otlp-proto-grpc/src/opentelemetry/exporter/otlp/proto/grpc/exporter.py

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@
2121
from time import sleep
2222
from typing import Any, Callable, Dict, Generic, List, Optional
2323
from typing import Sequence as TypingSequence
24-
from typing import Text, TypeVar
24+
from typing import TypeVar
2525
from urllib.parse import urlparse
2626

2727
from backoff import expo
@@ -115,14 +115,12 @@ def _translate_value(value: Any) -> KeyValue:
115115
# )
116116

117117
else:
118-
raise Exception(
119-
"Invalid type {} of value {}".format(type(value), value)
120-
)
118+
raise Exception(f"Invalid type {type(value)} of value {value}")
121119

122120
return any_value
123121

124122

125-
def _translate_key_values(key: Text, value: Any) -> KeyValue:
123+
def _translate_key_values(key: str, value: Any) -> KeyValue:
126124
return KeyValue(key=key, value=_translate_value(value))
127125

128126

exporter/opentelemetry-exporter-otlp-proto-grpc/src/opentelemetry/exporter/otlp/proto/grpc/trace_exporter/__init__.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -147,7 +147,7 @@ def _translate_context_trace_state(self, sdk_span: ReadableSpan) -> None:
147147
if sdk_span.context.trace_state is not None:
148148
self._collector_span_kwargs["trace_state"] = ",".join(
149149
[
150-
"{}={}".format(key, value)
150+
f"{key}={value}"
151151
for key, value in (sdk_span.context.trace_state.items())
152152
]
153153
)
@@ -302,7 +302,7 @@ def _translate_data(
302302

303303
self._collector_span_kwargs["kind"] = getattr(
304304
CollectorSpan.SpanKind,
305-
"SPAN_KIND_{}".format(sdk_span.kind.name),
305+
f"SPAN_KIND_{sdk_span.kind.name}",
306306
)
307307

308308
instrumentation_library_spans.spans.append(

exporter/opentelemetry-exporter-otlp-proto-grpc/tests/performance/benchmarks/test_benchmark_trace_exporter.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ def get_tracer_with_processor(span_processor_class):
3333
return tracer
3434

3535

36-
class MockTraceServiceStub(object):
36+
class MockTraceServiceStub:
3737
def __init__(self, channel):
3838
self.Export = lambda *args, **kwargs: None
3939

@@ -51,8 +51,8 @@ def create_spans_to_be_exported():
5151
)
5252
for i in range(10):
5353
span.set_attribute(
54-
"benchmarkAttribute_{}".format(i),
55-
"benchmarkAttrValue_{}".format(i),
54+
f"benchmarkAttribute_{i}",
55+
f"benchmarkAttrValue_{i}",
5656
)
5757
span.end()
5858

@@ -79,8 +79,8 @@ def create_spans_to_be_exported():
7979
)
8080
for i in range(10):
8181
span.set_attribute(
82-
"benchmarkAttribute_{}".format(i),
83-
"benchmarkAttrValue_{}".format(i),
82+
f"benchmarkAttribute_{i}",
83+
f"benchmarkAttrValue_{i}",
8484
)
8585
span.end()
8686

exporter/opentelemetry-exporter-otlp-proto-http/src/opentelemetry/exporter/otlp/proto/http/trace_exporter/encoder/__init__.py

Lines changed: 4 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414

1515
import logging
1616
from collections import abc
17-
from typing import Any, List, Optional, Sequence, Text
17+
from typing import Any, List, Optional, Sequence
1818

1919
from opentelemetry.proto.collector.trace.v1.trace_service_pb2 import (
2020
ExportTraceServiceRequest as PB2ExportTraceServiceRequest,
@@ -211,10 +211,7 @@ def _encode_trace_state(trace_state: TraceState) -> Optional[str]:
211211
pb2_trace_state = None
212212
if trace_state is not None:
213213
pb2_trace_state = ",".join(
214-
[
215-
"{}={}".format(key, value)
216-
for key, value in (trace_state.items())
217-
]
214+
[f"{key}={value}" for key, value in (trace_state.items())]
218215
)
219216
return pb2_trace_state
220217

@@ -283,13 +280,11 @@ def _encode_value(value: Any) -> PB2AnyValue:
283280
# elif isinstance(value, abc.Mapping):
284281
# pass
285282
else:
286-
raise Exception(
287-
"Invalid type {} of value {}".format(type(value), value)
288-
)
283+
raise Exception(f"Invalid type {type(value)} of value {value}")
289284
return any_value
290285

291286

292-
def _encode_key_value(key: Text, value: Any) -> PB2KeyValue:
287+
def _encode_key_value(key: str, value: Any) -> PB2KeyValue:
293288
any_value = _encode_value(value)
294289
return PB2KeyValue(key=key, value=any_value)
295290

exporter/opentelemetry-exporter-zipkin-json/setup.cfg

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,6 @@ classifiers =
2828
License :: OSI Approved :: Apache Software License
2929
Programming Language :: Python
3030
Programming Language :: Python :: 3
31-
Programming Language :: Python :: 3.5
3231
Programming Language :: Python :: 3.6
3332
Programming Language :: Python :: 3.7
3433
Programming Language :: Python :: 3.8
@@ -37,7 +36,7 @@ classifiers =
3736
Typing :: Typed
3837

3938
[options]
40-
python_requires = >=3.5
39+
python_requires = >=3.6
4140
package_dir=
4241
=src
4342
packages=find_namespace:

exporter/opentelemetry-exporter-zipkin-proto-http/setup.cfg

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,6 @@ classifiers =
2828
License :: OSI Approved :: Apache Software License
2929
Programming Language :: Python
3030
Programming Language :: Python :: 3
31-
Programming Language :: Python :: 3.5
3231
Programming Language :: Python :: 3.6
3332
Programming Language :: Python :: 3.7
3433
Programming Language :: Python :: 3.8
@@ -37,7 +36,7 @@ classifiers =
3736
Typing :: Typed
3837

3938
[options]
40-
python_requires = >=3.5
39+
python_requires = >=3.6
4140
package_dir=
4241
=src
4342
packages=find_namespace:

opentelemetry-api/tests/baggage/test_baggage_propagation.py

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -96,24 +96,21 @@ def test_invalid_header(self):
9696

9797
def test_header_too_long(self):
9898
long_value = "s" * (W3CBaggagePropagator._MAX_HEADER_LENGTH + 1)
99-
header = "key1={}".format(long_value)
99+
header = f"key1={long_value}"
100100
expected = {}
101101
self.assertEqual(self._extract(header), expected)
102102

103103
def test_header_contains_too_many_entries(self):
104104
header = ",".join(
105-
[
106-
"key{}=val".format(k)
107-
for k in range(W3CBaggagePropagator._MAX_PAIRS + 1)
108-
]
105+
[f"key{k}=val" for k in range(W3CBaggagePropagator._MAX_PAIRS + 1)]
109106
)
110107
self.assertEqual(
111108
len(self._extract(header)), W3CBaggagePropagator._MAX_PAIRS
112109
)
113110

114111
def test_header_contains_pair_too_long(self):
115112
long_value = "s" * (W3CBaggagePropagator._MAX_PAIR_LENGTH + 1)
116-
header = "key1=value1,key2={},key3=value3".format(long_value)
113+
header = f"key1=value1,key2={long_value},key3=value3"
117114
expected = {"key1": "value1", "key3": "value3"}
118115
with self.assertLogs(level=WARNING) as warning:
119116
self.assertEqual(self._extract(header), expected)

opentelemetry-api/tests/context/test_contextvars_context.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@
2222

2323
class TestContextVarsContext(ContextTestCases.BaseTest):
2424
def setUp(self) -> None:
25-
super(TestContextVarsContext, self).setUp()
25+
super().setUp()
2626
self.mock_runtime = patch.object(
2727
context,
2828
"_RUNTIME_CONTEXT",
@@ -31,5 +31,5 @@ def setUp(self) -> None:
3131
self.mock_runtime.start()
3232

3333
def tearDown(self) -> None:
34-
super(TestContextVarsContext, self).tearDown()
34+
super().tearDown()
3535
self.mock_runtime.stop()

opentelemetry-api/tests/propagators/test_composite.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -28,8 +28,8 @@ def get_as_list(dict_object, key):
2828
def mock_inject(name, value="data"):
2929
def wrapped(carrier=None, context=None, setter=None):
3030
carrier[name] = value
31-
setter.set({}, "inject_field_{}_0".format(name), None)
32-
setter.set({}, "inject_field_{}_1".format(name), None)
31+
setter.set({}, f"inject_field_{name}_0", None)
32+
setter.set({}, f"inject_field_{name}_1", None)
3333

3434
return wrapped
3535

@@ -44,7 +44,7 @@ def wrapped(carrier=None, context=None, getter=None):
4444

4545

4646
def mock_fields(name):
47-
return {"inject_field_{}_0".format(name), "inject_field_{}_1".format(name)}
47+
return {f"inject_field_{name}_0", f"inject_field_{name}_1"}
4848

4949

5050
class TestCompositePropagator(unittest.TestCase):

opentelemetry-sdk/tests/performance/resource-usage/trace/profile_resource_usage_batch_export.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@
2424
SPANS_PER_SECOND = 10_000
2525

2626

27-
class MockTraceServiceStub(object):
27+
class MockTraceServiceStub:
2828
def __init__(self, channel):
2929
self.Export = lambda *args, **kwargs: None
3030

opentelemetry-sdk/tests/performance/resource-usage/trace/profile_resource_usage_simple_export.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@
2424
SPANS_PER_SECOND = 10_000
2525

2626

27-
class MockTraceServiceStub(object):
27+
class MockTraceServiceStub:
2828
def __init__(self, channel):
2929
self.Export = lambda *args, **kwargs: None
3030

propagator/opentelemetry-propagator-b3/src/opentelemetry/propagators/b3/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ class B3MultiFormat(TextMapPropagator):
4242
SPAN_ID_KEY = "x-b3-spanid"
4343
SAMPLED_KEY = "x-b3-sampled"
4444
FLAGS_KEY = "x-b3-flags"
45-
_SAMPLE_PROPAGATE_VALUES = set(["1", "True", "true", "d"])
45+
_SAMPLE_PROPAGATE_VALUES = {"1", "True", "true", "d"}
4646
_trace_id_regex = re_compile(r"[\da-fA-F]{16}|[\da-fA-F]{32}")
4747
_span_id_regex = re_compile(r"[\da-fA-F]{16}")
4848

shim/opentelemetry-opentracing-shim/tests/testbed/otel_ot_shim_tracer.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ class MockTracer(opentracingshim.TracerShim):
1515
def __init__(self):
1616
tracer_provider = trace.TracerProvider()
1717
oteltracer = tracer_provider.get_tracer(__name__)
18-
super(MockTracer, self).__init__(oteltracer)
18+
super().__init__(oteltracer)
1919
exporter = InMemorySpanExporter()
2020
span_processor = SimpleSpanProcessor(exporter)
2121
tracer_provider.add_span_processor(span_processor)

shim/opentelemetry-opentracing-shim/tests/testbed/test_active_span_replacement/test_asyncio.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
from __future__ import print_function
2-
31
import asyncio
42

53
from ..otel_ot_shim_tracer import MockTracer

shim/opentelemetry-opentracing-shim/tests/testbed/test_active_span_replacement/test_threads.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
from __future__ import print_function
2-
31
from concurrent.futures import ThreadPoolExecutor
42

53
from ..otel_ot_shim_tracer import MockTracer

shim/opentelemetry-opentracing-shim/tests/testbed/test_client_server/test_asyncio.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
from __future__ import print_function
2-
31
import asyncio
42

53
import opentracing
@@ -16,7 +14,7 @@ class Server:
1614
def __init__(self, *args, **kwargs):
1715
tracer = kwargs.pop("tracer")
1816
queue = kwargs.pop("queue")
19-
super(Server, self).__init__(*args, **kwargs)
17+
super().__init__(*args, **kwargs)
2018

2119
self.tracer = tracer
2220
self.queue = queue

shim/opentelemetry-opentracing-shim/tests/testbed/test_client_server/test_threads.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
from __future__ import print_function
2-
31
from queue import Queue
42
from threading import Thread
53

@@ -17,7 +15,7 @@ class Server(Thread):
1715
def __init__(self, *args, **kwargs):
1816
tracer = kwargs.pop("tracer")
1917
queue = kwargs.pop("queue")
20-
super(Server, self).__init__(*args, **kwargs)
18+
super().__init__(*args, **kwargs)
2119

2220
self.daemon = True
2321
self.tracer = tracer

shim/opentelemetry-opentracing-shim/tests/testbed/test_common_request_handler/request_handler.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
from __future__ import print_function
2-
31
from opentracing.ext import tags
42

53
from ..utils import get_logger

shim/opentelemetry-opentracing-shim/tests/testbed/test_common_request_handler/test_asyncio.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
from __future__ import print_function
2-
31
import asyncio
42

53
from opentracing.ext import tags

shim/opentelemetry-opentracing-shim/tests/testbed/test_common_request_handler/test_threads.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
from __future__ import print_function
2-
31
from concurrent.futures import ThreadPoolExecutor
42

53
from opentracing.ext import tags

shim/opentelemetry-opentracing-shim/tests/testbed/test_late_span_finish/test_asyncio.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
from __future__ import print_function
2-
31
import asyncio
42

53
from ..otel_ot_shim_tracer import MockTracer

shim/opentelemetry-opentracing-shim/tests/testbed/test_late_span_finish/test_threads.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
from __future__ import print_function
2-
31
import time
42
from concurrent.futures import ThreadPoolExecutor
53

shim/opentelemetry-opentracing-shim/tests/testbed/test_listener_per_request/test_asyncio.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
from __future__ import print_function
2-
31
import asyncio
42

53
from opentracing.ext import tags

shim/opentelemetry-opentracing-shim/tests/testbed/test_listener_per_request/test_threads.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
from __future__ import print_function
2-
31
from concurrent.futures import ThreadPoolExecutor
42

53
from opentracing.ext import tags

shim/opentelemetry-opentracing-shim/tests/testbed/test_multiple_callbacks/test_asyncio.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
from __future__ import print_function
2-
31
import asyncio
42
import random
53

0 commit comments

Comments
 (0)