Python: Print a variable's name and value?

前端 未结 9 1628
一生所求
一生所求 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:05

    import inspect
    import re
    def debugPrint(x):
        frame = inspect.currentframe().f_back
        s = inspect.getframeinfo(frame).code_context[0]
        r = re.search(r"\((.*)\)", s).group(1)
        print("{} = {}".format(r,x))
    

    This won't work for all versions of python:

    inspect.currentframe()

    CPython implementation detail: This function relies on Python stack frame support in the interpreter, which isn’t guaranteed to exist in all implementations of Python. If running in an implementation without Python stack frame support this function returns None.

提交回复
热议问题