Python Style Guide

Posted on Apr 24, 2020

Formatting

Use type hints .

Write your code however is fastest and then use a formatter on it.

I like black . They have thought hard about the formatting and I just have to run one command once.

Classes

Classes are useful if you have to use the same variable in multiple functions, or want to concretely specify an object and it’s fields.

Classes can cause insanity if variables are being mutated.

If you cannot set a class variable on init it should not be a class variable.

Classes make writing tests more complicated.

Grouping related code can be done in a number of other ways.

Make sure the benefits of using a class outweigh the drawbacks.

Tests

Tests are great.

Patching and mocking other functions can be complicated.

Writing tests after writing your code is annoying.

Writing tests before writing your code makes life easier.

You may even end up writing more modular, understandable code.

Pytest is nice because it allows you to use normal assert statements.

unittest.mock has everything you need for mocking and patching other functions, but it will warp your brain a bit. I recommend the @patch() decorator . The only complicated thing here is that if you have multiple patches the first patch corresponds to the last variable.