Codementor Events

Quick Tips to Make Your Python Better Right Away

Published Oct 23, 2022

Quick Tips to Make your Python Better Right Away

Use a formatter - The first quick way to make your python code better to work with is to use a formatter. Consistent looking code is easy to scan. It makes the code look neater and organized. Other people can jump into your codebase with less friction.

There are a lot of code formatters out there. Black is a relatively new and popular one with minimal configuration.

Use a linter - Related to using a formatter, linters are another automatic tool that can find common errors and suggest fixes. There are a lot of common problems in code that almost everyone will write. Instead of relying on faulty memory to try to remember every mistake that could possibly be made, a linter will catch this for you. They can find problems like shadowing (re-naming) existing variables or signs of “code smell” like using too many variables.

Pylint is a popular linting software. It has a lot of configuration options and can be set to ignore lines if you don’t agree with the suggestions.

Manage resources with context managers - Context managers are a great tool to keep track of handling resources. One situation is opening and closing files. You need to open the file, read it, then close it. After opening the file you get a file handle, this is a resource, and they are limited on how many you can have. It is necessary to close them to give the resource back. It’s easy to over look closing the file and ending up with a bug where you exhaust your resources. In the case of files, you will hit the limit of open files allowed.

Context managers will automatically close the resource when the block of code is exited.

This is the syntax for context managers:

 with function_call() as resource_variable:
     resource_variable.use_thing(a, b, 3)

You can also write your own easily.

Read the docs - Python has so many documents to read that can help your code. The official documents for python has all of the functions and even example code for everything included in python. It is always good to skim through and see if there is a function that might be better for your code. PEP is another good resource for understanding features. This is where python features get discussed before being implemented.

Python docs

What is PEP
PEP 8, The PEP for style (What is your formatter and linter doing)

Discover and read more posts from Matthew Tejo
get started