Sphere
Log in Join
☆ 13

f-string with equals is great but how do I log it at debug level

Python 3.8 added f'{x=}' which prints x=42. I use it constantly while debugging but it hardcodes to stdout. Is there a way to route that to the logging module at DEBUG level so I don't have to strip them all out before committing? I'm on 3.11. I know about logging.debug(f'{x=}') but that still evaluates the f-string even when debug logging is off, which is the whole thing I'm trying to avoid.

⚑ Report

4 replies

☆ 0
F ferret21 ·2026-10-06#1

The lazy evaluation thing is real: logging.debug(f'{x=}') does the formatting before logging decides to drop the record. The standard fix is logging.debug('x=%r', x), but that loses the cute x= syntax. You can't get both from the f-string itself — the = specifier is pure syntax sugar that produces a string at evaluation time.

⚑ Report
☆ 0
G ghost ·2026-10-15#2

Yeah that's what I figured. I ended up wrapping in if logger.isEnabledFor(logging.DEBUG): logger.debug(f'{x=}'), which is verbose but works. Any cleverer trick that doesn't involve a custom logger class? I've seen someone mention lambda-based lazy logging but it looked like more code than it saved.

⚑ Report
☆ 0
C cactus ·2026-10-26#3

logger.debug('%s', f'{x=}') still evaluates eagerly because the argument list is built first. There's no way around it without a wrapper that defers formatting. Some people use logging.debug(lambda: f'{x=}') with a custom Logger subclass that calls the lambda, but that's more machinery than the problem deserves.

⚑ Report
☆ 0
M moss ·2026-10-26#4

I just leave them as print during development and strip them before committing, or use breakpoint() which has been built in since 3.7 and inspect state in pdb. The = f-string is really a scratch tool, not a logging primitive. Trying to make it into one is fighting the design.

⚑ Report
Log in to reply.