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.](https://media2.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fxgy6edh62kfpnmcezxdf.png)
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.](https://media2.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Faseq2bwtqq7gcvefbnii.png)
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"
}
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 |
I hope some of these hints help you make your Python code even prettier!
Top comments (0)