Skip to content

Instantly share code, notes, and snippets.

@atombrella
Created February 4, 2022 10:20
Show Gist options
  • Save atombrella/4cf3b7e9d2c7c12a28da9acd3e92cadc to your computer and use it in GitHub Desktop.
Save atombrella/4cf3b7e9d2c7c12a28da9acd3e92cadc to your computer and use it in GitHub Desktop.

Add type annotations

PEP 484 and other PEP improve the expressiveness of this new addition. In my experience, it greatly improves the readability of the code, and as a bonus, IDE assistance. MyPy, Pyright, Pyre are possible choices for static type checkers that you can add to your CI/CD pipelines. MyPy seems to be the one that most people use.

Note that Python does not enforce them by run-time, they are purely a tool for improving maintenability and readability of the code base.

There are many different advantages, e.g., you may have inconsistent arguments and return types in various places.

If you already used them as comments, you can use com2ann to speed up the process of converting them to Python 3 style type annotations.

Monitor your asserts

If you find a bunch of assertions in the test suite using assertTrue or assertFalse, the quality of the tests can be improve by using more precise assertions, e.g., assertIsNone, assertGreaterThan etc. You can use flake8-assertive to find them, and replace them.

Use literals instead for dictionaries, sets and lists

If nanoseconds (and being more Pythonic) are important to you, using literals are a bit faster than dict(...) and list(....). flake8-comprehensions can help you find these constructs, and update them.

Add more tests

Monitor your test suite with a code coverage tool to find code that are not covered by tests. Please note that a high test coverage percentage does not necessarily mean that all possible paths of the code are covered. You may not tests for all values of the parameters. For this reason, it is also easier to get a better overview by not using inline if-else constructs, e.g.,

update = regr.body if update is None else update
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment