DEV Community

Cover image for 4 Python hints
Tom Nijhof
Tom Nijhof

Posted on

1

4 Python hints

Cover image by atul prajapati from Pixabay

Sometimes I discover new things Python can do. These are 4 hints that help you in small ways to improve your code.

Print overwrite

Python print function can overwrite the previous print if end=”\r” is added.

print(f"processing {i}", end="\r")

On the left a print statement in a for-loop without end=\r, it prints out a hundred lines. On the right the same for-loop but now the print statement has end=\r, it now only shows the last printed line.

On the left a print statement in a for-loop without end=\r, it prints out a hundred lines. On the right the same for-loop but now the print statement has end=\r, it now only shows the last printed line.

Parameters with limited options

You might be in a situation where you have a limited set of options. You can do nothing and hope this goes okay, this is technically an option. However, a more elegant solution is the Literal type. This type can have multiple options and editors can pick these up to give you good type hints.

from typing import Literal
def change_background_2(new_color: Literal["red", "green", "blue"]):
if new_color.lower() == "red":
print("background red")
elif new_color.lower() == "green":
print("background green")
elif new_color.lower() == "blue":
print("background blue")
else:
raise ValueError(f"The color {new_color.name} cannot be used for the backround")
change_background_2("green")

Vscode auto-completing with the options red, green, and blue that were given in the Literal type hint.

Vscode auto-completing with the options red, green, and blue that were given in the Literal type hint.

I am not a huge fan of Literal given it still allows you to fill wrong values and sharing the options is a bit clumsy. Enum is an easy way to create a simple object that can do the same.

from enum import Enum, auto
class Color(Enum):
red = auto()
blue = auto()
green = auto()
def change_background(new_color: Color):
if new_color == Color.red:
print("background red")
elif new_color == Color.green:
print("background green")
elif new_color == Color.blue:
print("background blue")
else:
raise ValueError(f"The color {new_color.name} cannot be used for the backround")
change_background(Color.green)

Json pretty dump

Normally json dump puts everything on one line. This is great if file size is a concern but it is not great for readability. By adding indent to dump or dumps you can make the json readable for humans.

import json
dict = {"hello": "world", "goodbye": "Mars"}
print(json.dumps(dict, indent=4))

    {
      "hello": "world",
      "goodbye": "Mars"
    }
Enter fullscreen mode Exit fullscreen mode

Very big or small numbers

If you have a number with a lot of digits you can split it up by using underscores. You can place it anywhere in the number. If you have a number with a lot of leading zeros you can use scientific notation. Scientific notation for a million, a 1 with 6 zeros, is 1e6. Scientific notation can also be used for very small numbers, 2e-2 equals 0.02.

10_0000_0 + 1e3 + 1e-2
# result: 1001000.01
view raw big_numbers.py hosted with ❤ by GitHub



I hope some of these hints help you make your Python code even prettier!

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay