Python: Print a variable's name and value?

前端 未结 9 1645
一生所求
一生所求 2020-12-13 08:21

When debugging, we often see print statements like these:

print x        # easy to type, but no context
print \'x=\',x   # more context, harder to type
12
x=         


        
9条回答
  •  北海茫月
    2020-12-13 09:08

    Python 3.8 f-string = syntax

    It has arrived!

    #!/usr/bin/env python3
    foo = 1
    bar = 2
    print(f"{foo=} {bar=}")
    

    output:

    foo=1 bar=2 
    

    Added in commit https://github.com/python/cpython/commit/9a4135e939bc223f592045a38e0f927ba170da32 "Add f-string debugging using '='." which documents:

    f-strings now support =  for quick and easy debugging
    -----------------------------------------------------
    
    Add ``=`` specifier to f-strings. ``f'{expr=}'`` expands
    to the text of the expression, an equal sign, then the repr of the
    evaluated expression.  So::
    
      x = 3
      print(f'{x*9 + 15=}')
    
    Would print ``x*9 + 15=42``.
    

    so it also works for arbitrary expressions. Nice!

提交回复
热议问题