Skip to content
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

use f-strings where possible #2131

Merged
merged 5 commits into from
Sep 20, 2021
Merged
Show file tree
Hide file tree
Changes from 4 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
Original file line number Diff line number Diff line change
Expand Up @@ -123,9 +123,9 @@ def __init__(self, thrift_url="", auth=None, timeout_in_millis=None):

# set basic auth header
if auth is not None:
auth_header = "{}:{}".format(*auth)
auth_header = f"{auth[0]}:{auth[1]}"
decoded = base64.b64encode(auth_header.encode()).decode("ascii")
basic_auth = dict(Authorization="Basic {}".format(decoded))
basic_auth = dict(Authorization=f"Basic {decoded}")
self.http_transport.setCustomHeaders(basic_auth)

def submit(self, batch: jaeger.Batch):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -320,16 +320,12 @@ def test_otlp_exporter_endpoint(self, mock_secure, mock_insecure):
self.assertEqual(
1,
mock_method.call_count,
"expected {} to be called for {} {}".format(
mock_method, endpoint, insecure
),
f"expected {mock_method} to be called for {endpoint} {insecure}",
)
self.assertEqual(
expected_endpoint,
mock_method.call_args[0][0],
"expected {} got {} {}".format(
expected_endpoint, mock_method.call_args[0][0], endpoint
),
f"expected {expected_endpoint} got {mock_method.call_args[0][0]} {endpoint}",
)
mock_method.reset_mock()

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ def ipv4(self, address: IpInput) -> None:
ipv4_address = ipaddress.ip_address(address)
if not isinstance(ipv4_address, ipaddress.IPv4Address):
raise ValueError(
"%r does not appear to be an IPv4 address" % address
f"{address!r} does not appear to be an IPv4 address"
)
self._ipv4 = ipv4_address

Expand All @@ -80,6 +80,6 @@ def ipv6(self, address: IpInput) -> None:
ipv6_address = ipaddress.ip_address(address)
if not isinstance(ipv6_address, ipaddress.IPv6Address):
raise ValueError(
"%r does not appear to be an IPv6 address" % address
f"{address!r} does not appear to be an IPv6 address"
)
self._ipv6 = ipv6_address
4 changes: 2 additions & 2 deletions opentelemetry-api/src/opentelemetry/attributes/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -153,8 +153,8 @@ def __init__(
self._immutable = immutable

def __repr__(self):
return "{}({}, maxlen={})".format(
type(self).__name__, dict(self._dict), self.maxlen
return (
f"{type(self).__name__}({dict(self._dict)}, maxlen={self.maxlen})"
)

def __getitem__(self, key):
Expand Down
2 changes: 1 addition & 1 deletion opentelemetry-api/src/opentelemetry/trace/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -537,7 +537,7 @@ def use_span(
span.set_status(
Status(
status_code=StatusCode.ERROR,
description="{}: {}".format(type(exc).__name__, exc),
description=f"{type(exc).__name__}: {exc}",
)
)
raise
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -100,11 +100,7 @@ def inject(
span_context = span.get_span_context()
if span_context == trace.INVALID_SPAN_CONTEXT:
return
traceparent_string = "00-{trace_id}-{span_id}-{:02x}".format(
span_context.trace_flags,
trace_id=format_trace_id(span_context.trace_id),
span_id=format_span_id(span_context.span_id),
)
traceparent_string = f"00-{format_trace_id(span_context.trace_id)}-{format_span_id(span_context.span_id)}-{span_context.trace_flags:02x}"
setter.set(carrier, self._TRACEPARENT_HEADER_NAME, traceparent_string)
if span_context.trace_state:
tracestate_string = span_context.trace_state.to_header()
Expand Down
19 changes: 4 additions & 15 deletions opentelemetry-api/src/opentelemetry/trace/span.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,7 @@

_TRACECONTEXT_MAXIMUM_TRACESTATE_KEYS = 32
_delimiter_pattern = re.compile(r"[ \t]*,[ \t]*")
_member_pattern = re.compile(
"({})(=)({})[ \t]*".format(_KEY_FORMAT, _VALUE_FORMAT)
)
_member_pattern = re.compile(f"({_KEY_FORMAT})(=)({_VALUE_FORMAT})[ \t]*")
_logger = logging.getLogger(__name__)


Expand Down Expand Up @@ -245,7 +243,7 @@ def __len__(self) -> int:

def __repr__(self) -> str:
pairs = [
"{key=%s, value=%s}" % (key, value)
f"{{key={key}, value={value}}}"
for key, value in self._dict.items()
]
return str(pairs)
Expand Down Expand Up @@ -478,16 +476,7 @@ def __delattr__(self, *args: str) -> None:
)

def __repr__(self) -> str:
return (
"{}(trace_id=0x{}, span_id=0x{}, trace_flags=0x{:02x}, trace_state={!r}, is_remote={})"
).format(
type(self).__name__,
format_trace_id(self.trace_id),
format_span_id(self.span_id),
self.trace_flags,
self.trace_state,
self.is_remote,
)
return f"{type(self).__name__}(trace_id=0x{format_trace_id(self.trace_id)}, span_id=0x{format_span_id(self.span_id)}, trace_flags=0x{self.trace_flags:02x}, trace_state={self.trace_state!r}, is_remote={self.is_remote})"


class NonRecordingSpan(Span):
Expand Down Expand Up @@ -540,7 +529,7 @@ def record_exception(
pass

def __repr__(self) -> str:
return "NonRecordingSpan({!r})".format(self._context)
return f"NonRecordingSpan({self._context!r})"


INVALID_SPAN_ID = 0x0000000000000000
Expand Down
4 changes: 2 additions & 2 deletions opentelemetry-api/src/opentelemetry/util/_providers.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,12 +32,12 @@ def _load_provider(
try:
entry_point = next(
iter_entry_points(
"opentelemetry_{}".format(provider),
f"opentelemetry_{provider}",
name=cast(
str,
environ.get(
provider_environment_variable,
"default_{}".format(provider),
f"default_{provider}",
),
),
)
Expand Down
2 changes: 1 addition & 1 deletion opentelemetry-api/src/opentelemetry/util/_time.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@

if version_info.minor < 7:
getLogger(__name__).warning( # pylint: disable=logging-not-lazy
"You are using Python 3.%s. This version does not support timestamps "
"You are using Python 3.%s. This version does not support timestamps " # pylint: disable=C0209
"with nanosecond precision and the OpenTelemetry SDK will use "
"millisecond precision instead. Please refer to PEP 564 for more "
"information. Please upgrade to Python 3.7 or newer to use nanosecond "
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ def initialize():
logger.exception("Failed to auto initialize opentelemetry")
finally:
environ["PYTHONPATH"] = sub(
r"{}{}?".format(dirname(abspath(__file__)), pathsep),
fr"{dirname(abspath(__file__))}{pathsep}?",
srikanthccv marked this conversation as resolved.
Show resolved Hide resolved
"",
environ["PYTHONPATH"],
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,11 +38,9 @@ def wrapper(package=None):
except subprocess.SubprocessError as exp:
cmd = getattr(exp, "cmd", None)
if cmd:
msg = 'Error calling system command "{0}"'.format(
" ".join(cmd)
)
msg = f'Error calling system command "{" ".join(cmd)}"'
if package:
msg = '{0} for package "{1}"'.format(msg, package)
msg = f'{msg} for package "{package}"'
raise RuntimeError(msg)

return wrapper
Expand Down Expand Up @@ -81,9 +79,7 @@ def _pip_check():
for package_tup in libraries.values():
for package in package_tup:
if package.lower() in pip_check_lower:
raise RuntimeError(
"Dependency conflict found: {}".format(pip_check)
)
raise RuntimeError(f"Dependency conflict found: {pip_check}")


def _is_installed(req):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,7 @@ def __init__(self, required, found=None):
self.found = found

def __str__(self):
return 'DependencyConflict: requested: "{0}" but found: "{1}"'.format(
self.required, self.found
)
return f'DependencyConflict: requested: "{self.required}" but found: "{self.found}"'


def get_dist_dependency_conflicts(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ class DictHeaderSetter(Setter):
def set(self, carrier, key, value): # pylint: disable=no-self-use
old_value = carrier.get(key, "")
if old_value:
value = "{0}, {1}".format(old_value, value)
value = f"{old_value}, {value}"
carrier[key] = value


Expand Down Expand Up @@ -115,11 +115,7 @@ def inject(
setter.set(
carrier,
header_name,
"00-{trace_id}-{span_id}-{:02x}".format(
span_context.trace_flags,
trace_id=format_trace_id(span_context.trace_id),
span_id=format_span_id(span_context.span_id),
),
f"00-{format_trace_id(span_context.trace_id)}-{format_span_id(span_context.span_id)}-{span_context.trace_flags:02x}",
)
setter.set(
carrier,
Expand Down
4 changes: 1 addition & 3 deletions opentelemetry-instrumentation/tests/test_dependencies.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,9 +50,7 @@ def test_get_dependency_conflicts_mismatched_version(self):
self.assertTrue(isinstance(conflict, DependencyConflict))
self.assertEqual(
str(conflict),
'DependencyConflict: requested: "pytest == 5000" but found: "pytest {0}"'.format(
pytest.__version__
),
f'DependencyConflict: requested: "pytest == 5000" but found: "pytest {pytest.__version__}"',
)

def test_get_dist_dependency_conflicts(self):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -91,9 +91,7 @@ def _import_tracer_provider_config_components(
entry_point = component_entry_points.get(selected_component, None)
if not entry_point:
raise RuntimeError(
"Requested component '{}' not found in entry points for '{}'".format(
selected_component, entry_point_name
)
f"Requested component '{selected_component}' not found in entry points for '{entry_point_name}'"
)

component_impl = entry_point.load()
Expand All @@ -116,9 +114,7 @@ def _import_exporters(
if issubclass(exporter_impl, SpanExporter):
trace_exporters[exporter_name] = exporter_impl
else:
raise RuntimeError(
"{0} is not a trace exporter".format(exporter_name)
)
raise RuntimeError(f"{exporter_name} is not a trace exporter")
return trace_exporters


Expand All @@ -133,7 +129,7 @@ def _import_id_generator(id_generator_name: str) -> IdGenerator:
if issubclass(id_generator_impl, IdGenerator):
return id_generator_impl

raise RuntimeError("{0} is not an IdGenerator".format(id_generator_name))
raise RuntimeError(f"{id_generator_name} is not an IdGenerator")


def _initialize_components():
Expand Down
37 changes: 9 additions & 28 deletions opentelemetry-sdk/src/opentelemetry/sdk/trace/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -219,7 +219,7 @@ def _submit_and_await(
self,
func: Callable[[SpanProcessor], Callable[..., None]],
*args: Any,
**kwargs: Any
**kwargs: Any,
):
futures = []
for sp in self._span_processors:
Expand Down Expand Up @@ -442,12 +442,10 @@ def to_json(self, indent=4):
if self.parent is not None:
if isinstance(self.parent, Span):
ctx = self.parent.context
parent_id = "0x{}".format(
trace_api.format_span_id(ctx.span_id)
)
parent_id = f"0x{trace_api.format_span_id(ctx.span_id)}"
elif isinstance(self.parent, SpanContext):
parent_id = "0x{}".format(
trace_api.format_span_id(self.parent.span_id)
parent_id = (
f"0x{trace_api.format_span_id(self.parent.span_id)}"
)

start_time = None
Expand Down Expand Up @@ -484,12 +482,8 @@ def to_json(self, indent=4):
@staticmethod
def _format_context(context):
x_ctx = OrderedDict()
x_ctx["trace_id"] = "0x{}".format(
trace_api.format_trace_id(context.trace_id)
)
x_ctx["span_id"] = "0x{}".format(
trace_api.format_span_id(context.span_id)
)
x_ctx["trace_id"] = f"0x{trace_api.format_trace_id(context.trace_id)}"
x_ctx["span_id"] = f"0x{trace_api.format_span_id(context.span_id)}"
x_ctx["trace_state"] = repr(context.trace_state)
return x_ctx

Expand Down Expand Up @@ -612,16 +606,7 @@ def __init__(
)

def __repr__(self):
return "{}(max_span_attributes={}, max_events_attributes={}, max_link_attributes={}, max_attributes={}, max_events={}, max_links={}, max_attribute_length={})".format(
type(self).__name__,
self.max_span_attribute_length,
self.max_event_attributes,
self.max_link_attributes,
self.max_attributes,
self.max_events,
self.max_links,
self.max_attribute_length,
)
return f"{type(self).__name__}(max_span_attributes={self.max_span_attribute_length}, max_events_attributes={self.max_event_attributes}, max_link_attributes={self.max_link_attributes}, max_attributes={self.max_attributes}, max_events={self.max_events}, max_links={self.max_links}, max_attribute_length={self.max_attribute_length})"

@classmethod
def _from_env_if_absent(
Expand Down Expand Up @@ -759,9 +744,7 @@ def __init__(
self._links = BoundedList.from_seq(self._limits.max_links, links)

def __repr__(self):
return '{}(name="{}", context={})'.format(
type(self).__name__, self._name, self._context
)
return f'{type(self).__name__}(name="{self._name}", context={self._context})'

def _new_events(self):
return BoundedList(self._limits.max_events)
Expand Down Expand Up @@ -889,9 +872,7 @@ def __exit__(
self.set_status(
Status(
status_code=StatusCode.ERROR,
description="{}: {}".format(
exc_type.__name__, exc_val
),
description=f"{exc_type.__name__}: {exc_val}",
)
)

Expand Down
14 changes: 3 additions & 11 deletions opentelemetry-sdk/src/opentelemetry/sdk/trace/sampling.py
Original file line number Diff line number Diff line change
Expand Up @@ -145,9 +145,7 @@ class SamplingResult:
"""

def __repr__(self) -> str:
return "{}({}, attributes={})".format(
type(self).__name__, str(self.decision), str(self.attributes)
)
return f"{type(self).__name__}({str(self.decision)}, attributes={str(self.attributes)})"

def __init__(
self,
Expand Down Expand Up @@ -271,7 +269,7 @@ def should_sample(
)

def get_description(self) -> str:
return "TraceIdRatioBased{{{}}}".format(self._rate)
return f"TraceIdRatioBased{{{self._rate}}}"


class ParentBased(Sampler):
Expand Down Expand Up @@ -342,13 +340,7 @@ def should_sample(
)

def get_description(self):
return "ParentBased{{root:{},remoteParentSampled:{},remoteParentNotSampled:{}," "localParentSampled:{},localParentNotSampled:{}}}".format(
self._root.get_description(),
self._remote_parent_sampled.get_description(),
self._remote_parent_not_sampled.get_description(),
self._local_parent_sampled.get_description(),
self._local_parent_not_sampled.get_description(),
)
return f"ParentBased{{root:{self._root.get_description()},remoteParentSampled:{self._remote_parent_sampled.get_description()},remoteParentNotSampled:{self._remote_parent_not_sampled.get_description()},localParentSampled:{self._local_parent_sampled.get_description()},localParentNotSampled:{self._local_parent_not_sampled.get_description()}}}"


DEFAULT_OFF = ParentBased(ALWAYS_OFF)
Expand Down
8 changes: 3 additions & 5 deletions opentelemetry-sdk/src/opentelemetry/sdk/util/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,9 +54,7 @@ def __init__(self, maxlen: Optional[int]):
self._lock = threading.Lock()

def __repr__(self):
return "{}({}, maxlen={})".format(
type(self).__name__, list(self._dq), self._dq.maxlen
)
return f"{type(self).__name__}({list(self._dq)}, maxlen={self._dq.maxlen})"

def __getitem__(self, index):
return self._dq[index]
Expand Down Expand Up @@ -113,8 +111,8 @@ def __init__(self, maxlen: Optional[int]):
self._lock = threading.Lock() # type: threading.Lock

def __repr__(self):
return "{}({}, maxlen={})".format(
type(self).__name__, dict(self._dict), self.maxlen
return (
f"{type(self).__name__}({dict(self._dict)}, maxlen={self.maxlen})"
)

def __getitem__(self, key):
Expand Down
Loading