简体   繁体   中英

Python: print variable name and value easily

I want to use a function that can automatically print out the variable and the value. Like shown below:

num = 3
coolprint(num)

output:

num = 3

furthermore, it would be cool if it could also do something like this:

variable.a = 3
variable.b = 5
coolprint(vars(variable))

output:

vars(variable) = {'a': 3, 'b': 5}

Is there any function like this already out there? Or should I make my own? Thanks

An official way to accomplish this task sadly doesn't exist even though it could be useful for many people. What I would suggest and I have used it sometimes in the past is the following(I am not sure if this is the best way to do it).

Basically what you can do is to create a custom object that mimics one Python's data type per time. Bellow you can find an example for an integer.

class CustomVariable(object):

    def __init__(self, name, value):
        self.name = name
        self.value = value

    def __str__(self):
        return "{} = {}".format(self.name, self.value)

    def __add__(self, val) :
        return self.value + val


myVar = CustomVariable("myVar", 15)
print myVar
myVar = myVar + 5
print myVar

Output:
myVar = 15
myVar = 20

Check the special method named "___str____"

I have discovered the answer is No. There is no way to do this. However, your best bet is something like this:

from pprint import pprint

def crint(obj, name):

    if isinstance(obj, dict):
        print '\n' + name + ' = '
        pprint(obj)

    else:
        print '\n' + name + ' = ' + str(obj)

that way you can just do:

crint(vars(table.content[0]), 'vars(table.content[0])')

or:

j = 3
crint(j, 'j')

This lambda-based solution works well enough for me, though perhaps not in every case. It is very simple and only consumes one line.

coolprint = lambda *w: [print(x,'=',eval(x)) for x in w]

Exmaple..

coolprint = lambda *w: [print(x,'=',eval(x)) for x in w]

a, *b, c = [1, 2, 3, 4, 5]

coolprint('a')
coolprint('b','c')
coolprint('a','b','c')
coolprint('c','b','b','a','b','c')

which produces..

a = 1
b = [2, 3, 4]
c = 5
a = 1
b = [2, 3, 4]
c = 5
a = 1
b = [2, 3, 4]
c = 5
c = 5
b = [2, 3, 4]
b = [2, 3, 4]
a = 1
b = [2, 3, 4]
c = 5

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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