0

For debugging I often want to print a variable out. I do this with for example:

print("cat_litter", cat_litter)

That is I print the variable name and its value. Is it possible to define a function to do this for me so I could call something like "printwithname(cat_litter)" for example.

Simd
  • 19,447
  • 42
  • 136
  • 271

1 Answers1

8

No function needed! Python 3.8+ f-strings support this kind of printing directly:

foo = 1
bar = 2
baz = "Something else"
print(f'{foo=}, {bar=}, {baz=}')

https://docs.python.org/3/whatsnew/3.8.html#f-strings-support-for-self-documenting-expressions-and-debugging

Python 3.6 -> 3.7 Workaround:

Python: Print a variable's name and value?

Brendano257
  • 553
  • 5
  • 10
  • What version of python does this need? – Simd Dec 24 '20 at 19:00
  • Python 3.6 or later with f string support. – dawg Dec 24 '20 at 19:00
  • @dawg thanks. I think 3.6 should be doable for me. What can you do if you only have 3.5? – Simd Dec 24 '20 at 19:01
  • @Anush, I'd test this for yourself. This kind of f-string use is 3.8+, but f-strings themselves were included in 3.6. See https://docs.python.org/3/whatsnew/3.8.html#f-strings-support-for-self-documenting-expressions-and-debugging – Brendano257 Dec 24 '20 at 19:04
  • No good options prior to Python 3.6. Python variables do not general support name introspection other than with functions or writing your own object that does. You could look at the inspect module but really -- it is easier to upgrade to Python 3.6 or later. – dawg Dec 24 '20 at 19:06
  • The link is very helpful and also quite simple, thank you. – Simd Dec 24 '20 at 19:08
  • If you think this question has an answer somewhere else in this site - [flag it as duplicate](https://stackoverflow.com/help/privileges/flag-posts) instead of posting a link to an answer as an answer... – Tomerikoo Dec 24 '20 at 19:23