1

I want to debug my python program using only print, but I don't want to repeat my self every row.

for e.g, instead of writing:

print(f"var1 = {var1}")
print(f"var2 = {var2}")

I would like to write:

debug(var1, var2) or debug("var1", "var2")

and get

>>> var1 = 3
>>> var2 = 8

I wrote a short function doing this

def debug_globals(*vars):
    for var in vars:
        try:
            print(f'{var} = {repr(eval(var))}')
        except NameError as e:
            print(e)

It works for globals variables, but won't work for debuging local variables inside a function .

>>> x = 2
>>> y = 3

>>> def foo():
...    x = 5
...    debug_globals('x', 'y')
>>> foo()
x = 2
y = 3

How can I improve my "debug" function?

2 Answers 2

1

The following will probably do what you want:

import inspect

def debug(*names):
    out_frame = inspect.currentframe().f_back
    globalz = out_frame.f_globals
    localz  =out_frame.f_locals
    for name in names:
        value = eval(name, globalz, localz)
        print(name, "=", value)
    del out_frame

x = 2
y = 3
debug("x", "y")
Sign up to request clarification or add additional context in comments.

Comments

1

Use Python 3.8's new feature:

Python 3.8.0 (tags/v3.8.0:fa919fd, Oct 14 2019, 19:37:50) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> var1 = 3
>>> var2 = 8
>>> print(f'{var1=} {var2=}')
var1=3 var2=8

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.