简体   繁体   English

如何打印变量的名称和值?

[英]How to print the name and value of a variable?

This is what I have in mind because I find myself typing the name twice whenever I want to inspect the value of a variable: 这就是我要记住的,因为每当我要检查变量的值时,我都会两次键入名称:

a = 1
my_print(a)  # "a: 1"

Is this possible in Python? 这在Python中可行吗?

If you are in control of the calling function, you can hack this to work reasonably well like: 如果您可以控制调用函数,则可以修改此函数使其正常运行,例如:

Code: 码:

import inspect

def print_name_and_value(var):
    lines = inspect.stack()[1][4]
    var_name = ''.join(lines).strip().split('(')[-1].split(')')[0]
    print("%s: %d" % (var_name, var))

a = 5
print_name_and_value(a)

Results: 结果:

a: 5

How does this work? 这是如何运作的?

The inspect module can be used to inspect the caller, and get the line of code used by the caller. 检查模块可用于检查调用方,并获取调用方使用的代码行。 With a bit of string hacking the variable name (assuming it is a simple variable and not a more complex expression) can be gathered from the source code. 只需用一点点字符串就可以从源代码中收集变量名(假设它是一个简单的变量,而不是一个更复杂的表达式)。

I would say "no", and any other magic doable is just... too much magic. 我会说“不”,其他任何可行的魔术就是……太多的魔术。

However there's something you can do, and that's looking at the stack trace using the inspect module . 但是 ,您可以做一些事情,那就是使用inspect模块查看堆栈跟踪。

import inspect


def my_print(thingy):
    # print("id(thingy)=%s" % id(thingy))
    previous_frame = inspect.currentframe().f_back
    # print("locals: %s" % previous_frame.f_locals)
    for variable_name, variable_value in previous_frame.f_locals.items():
        if id(variable_value) == id(thingy):
            return("%s: %s" % (variable_name, variable_value))

    # print("globals: %s" % previous_frame.f_globals)
    for variable_name, variable_value in previous_frame.f_globals.items():
        if id(variable_value) == id(thingy):
            return("%s: %s" % (variable_name, variable_value))


if __name__ == '__main__':
    a = 1
    print("Test %s" % my_print(a))  # "a: 1"
    list_thingy = [1, 2, 3]
    print("Test %s" % my_print(list_thingy))

    def and_within_function():
        d = {1: "a"}
        print("Test %s" % my_print(d))

    and_within_function()

But this is not reliable and I'd use it more as a curiosity , since there are plenty of "special cases". 但这是不可靠的, 出于好奇我会更多地使用它 ,因为有很多“特殊情况”。 For instance: the first 255 integers (I think) in Python occupy a specific memory address so, if you have two variables that are =1 I don't think you're gonna really be guaranteed which one is it. 例如:Python中的前255个整数(我认为)占用一个特定的内存地址,因此,如果您有两个等于=1变量,我认为您不会真正保证它是哪个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM