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!

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay