13

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

4
  • check pprint it may do what you want Commented Sep 6, 2017 at 18:09
  • 1
    Python doesn't support this. Functions only see objects, not variable names. coolprint has no idea that the 3 came from a variable named num. Commented Sep 6, 2017 at 18:09
  • 1
    It is simply not possibly to pinpoint the right variable, because you can have multiple variables pointing to the same value. Commented Sep 6, 2017 at 18:10
  • 4
    import sys; print(sys.getrefcount(0)) and you'll understand. Commented Sep 6, 2017 at 18:11

5 Answers 5

26

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

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

This would output

# python=rocks
Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

0

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

Comments

0

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)

Comments

-2

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

2 Comments

Another possible alternative is to use a mapping data structure such as a dictionary.
See my answer for a Python-native way to do this from Python 3.8 on :)

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.