Slaknation
Slaknation

Reputation: 1926

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

Upvotes: 13

Views: 14604

Answers (5)

Lopofsky
Lopofsky

Reputation: 528

If you're interested, my approach was to go beyond the printing of var_name=var_value and incorporate timing & line of code as well:

https://raw.githubusercontent.com/Lopofsky/tales-of-the-ni/main/a_more_useful_print.py

from datetime import datetime
from inspect import currentframe, getframeinfo


def super_print(
    active=True,
    presentation="|#count@line - time|---> result",
    start=0, step=1,
    suffix="\n", endfix="\n"
):
    count = start
    last_time = datetime.now()

    def format_presentation(line_number, input_string):
        current_time = datetime.now()
        time_diff = current_time - last_time
        time_str = f"{time_diff.seconds}.{time_diff.microseconds}"
        formatted_line = (
            presentation
            .replace("count", str(count))
            .replace("line", str(line_number))
            .replace("time", time_str)
            .replace("result", input_string)
        )
        if 'result' not in presentation:
            formatted_line += f': {input_string}'
        return formatted_line

    def print_logger(string="", active=active):
        nonlocal count, last_time
        if active:
            caller_frame = currentframe().f_back
            line_number = getframeinfo(caller_frame).lineno
            formatted_string = ''.join([
                suffix,
                format_presentation(line_number, str(string)),
                endfix
            ])
            print(formatted_string)

        count += step
        last_time = datetime.now()

    return print_logger


if __name__ == "__main__":
    # Example usage
    pp = super_print(active=True, presentation=">line@time: `result`")

    pp('start')
    a_dict = {'a': 1}
    pp(a_dict)

Upvotes: 0

The Unfun Cat
The Unfun Cat

Reputation: 31928

From Python 3.8 there is a = for f-strings:

#!/usr/bin/env python3
python="rocks"
print(f"{python=}")

This would output

# python=rocks

Upvotes: 26

Paperclip Bob
Paperclip Bob

Reputation: 386

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

Upvotes: 3

Slaknation
Slaknation

Reputation: 1926

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')

Upvotes: -2

George
George

Reputation: 86

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____"

Upvotes: 0

Related Questions