DEV Community

Cover image for 4 Python hints
Tom Nijhof
Tom Nijhof

Posted on

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.


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.


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.

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.


    {
      "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.



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

Top comments (0)