---
title: Python Style Guide
description: What I have learned about writing Python after two years of using it to developing and maintaining critical business integrations.
---

[systems | willwatkinson ](https://systems.willwatkinson.com)

# [Python Style Guide](https://systems.willwatkinson.com/python-style-guide)

 Written by [Will Watkinson](https://systems.willwatkinson.com/author/will-watkinson) | Apr 23, 2020 8:49:49 PM

### Formatting

Use [type hints](https://docs.python.org/3/library/typing.html).

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

I like [black](https://black.readthedocs.io/en/stable/). 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](https://docs.pytest.org/en/latest/) is nice because it allows you to use normal assert statements.

[unittest.mock](https://docs.python.org/3/library/unittest.mock.html) has everything you need for mocking and patching other functions, but it will warp your brain a bit. I recommend the [@patch() decorator](https://docs.python.org/3/library/unittest.mock.html#unittest.mock.patch). The only complicated thing here is that if you have multiple patches the first patch corresponds to the last variable.

[View full post](https://systems.willwatkinson.com/python-style-guide)

```json
{
  "@context" : "http://schema.org",
  "@type" : "BlogPosting",
  "author" : {
    "@type" : "Person",
    "name" : "Will Watkinson"
  },
  "dateModified" : "2020-04-24T18:56:55.226Z",
  "datePublished" : "2020-04-23T20:49:49Z",
  "headline" : "Python Style Guide",
  "image" : {
    "@type" : "ImageObject",
    "height" : 60,
    "url" : "/hs/hsstatic/content_shared_assets/static-1.4092/img/default-amp-logo.png",
    "width" : 60
  },
  "mainEntityOfPage" : "https://systems.willwatkinson.com/python-style-guide",
  "publisher" : {
    "@type" : "Organization",
    "logo" : {
      "@type" : "ImageObject",
      "height" : 60,
      "url" : "/hs/hsstatic/content_shared_assets/static-1.4092/img/default-amp-logo.png",
      "width" : 60
    },
    "name" : "systems"
  }
}
```