DEV Community

Cover image for Python print with line number and variable name
Andrey Sobolev
Andrey Sobolev

Posted on

Python print with line number and variable name

Sometimes you want to print something to the console (without breakpoints setup).

hello = "world"
print(hello)
>>> world
Enter fullscreen mode Exit fullscreen mode

While the program is small, there are no problems with this. Let's assume that you have started working with some class with ~ 3000 lines (legacy code) and you need to quickly look at any values. The number of "prints" increases, and it becomes not easy to understand from the first time which "print" refers to which variable. You can of course write like this.

print('hello=', hello)
Enter fullscreen mode Exit fullscreen mode

Yes, that's better. But I would still like to see both the line number and the type of variable. And in some cases, the path to the file.

For such cases, I have written a small (and very useful) utility that will make your life easier. Let's try to install it.

pip install simple-print
Enter fullscreen mode Exit fullscreen mode

And print something.

from simple_print, import sprint

master = "yoda"

# Print the variable name with the line number
sprint(master) 

# Add blue paint
sprint(master, c="blue") 

# Add a white background
sprint(master, c="blue", b="on_white") 

# Add underline
sprint(master, c="blue", b="on_white", a="underline") 

# ADD the path to
sprint(master, c="blue", b="on_white", a="underline", p=True)

# Return as a string
s = sprint(master, s=True)
Enter fullscreen mode Exit fullscreen mode

Image description

And of course you can use indents for debugging in forloops:

def test_indent():

    fruits = ["lemon", "orange", "banana"]
    sprint(fruits, c="green")

    for fruit in fruits:
        sprint(fruit, c="yellow", i=4)

Enter fullscreen mode Exit fullscreen mode

Image description

The source code can be viewed here https://github.com/Sobolev5/simple-print

Productive development for you. Thanks for reading.

Top comments (0)