Skip to content

Commit 6f1a847

Browse files
authored
Remove warning about attribute/variable name conflicts in f-string magic (#418)
1 parent d43d91d commit 6f1a847

File tree

2 files changed

+3
-28
lines changed

2 files changed

+3
-28
lines changed

logfire/_internal/formatter.py

Lines changed: 1 addition & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -169,25 +169,7 @@ def _fstring_chunks(
169169
# We have an f-string AST node.
170170
# Now prepare the namespaces that we will use to evaluate the components.
171171
global_vars = frame.f_globals
172-
local_vars = {**frame.f_locals}
173-
# Add any values in kwargs (i.e. attributes) to `local_vars` so that they take precedence.
174-
# Warn the user if there's a conflict.
175-
for kwarg_name, kwarg_value in kwargs.items():
176-
# Check the same namespaces that Python uses, in the same order.
177-
for namespace in (local_vars, global_vars, frame.f_builtins):
178-
if kwarg_name in namespace:
179-
# No need to warn if they just passed the same value as an attribute, e.g. `foo=foo`.
180-
if namespace[kwarg_name] is not kwarg_value:
181-
warnings.warn(
182-
f'The attribute {kwarg_name!r} has the same name as a variable with a different value. '
183-
f'Using the attribute.',
184-
stacklevel=get_stacklevel(frame),
185-
)
186-
# No need to check the other namespaces either way,
187-
# since the earlier namespaces take precedence even in normal variable lookups.
188-
break
189-
# Set the attribute value regardless of whether it's also an existing variable.
190-
local_vars[kwarg_name] = kwarg_value
172+
local_vars = {**frame.f_locals, **kwargs}
191173

192174
# Now for the actual formatting!
193175
result: list[LiteralChunk | ArgChunk] = []

tests/test_logfire.py

Lines changed: 2 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1789,15 +1789,8 @@ def foo():
17891789
with logfire.span(f'span {GLOBAL_VAR} {local_var}'), logfire.span(f'span2 {local_var}'):
17901790
str(logfire.info(f'log {GLOBAL_VAR} {local_var}'))
17911791

1792-
with pytest.warns(UserWarning) as warnings:
1793-
logfire.info(f'log2 {local_var}', local_var=3, x=x)
1794-
assert str(warnings[0].message) == snapshot(
1795-
"The attribute 'local_var' has the same name as a variable with a different value. Using the attribute."
1796-
)
1797-
assert warnings[0].filename == __file__
1798-
frame = inspect.currentframe()
1799-
assert frame is not None
1800-
assert warnings[0].lineno == frame.f_lineno - 7
1792+
# Test that an attribute overrides a local variable
1793+
logfire.info(f'log2 {local_var}', local_var=3, x=x)
18011794

18021795
# Test the .log method which has the argument in a different place from the other methods.
18031796
logfire.log('error', f'log3 {GLOBAL_VAR}')

0 commit comments

Comments
 (0)