3 Code structure and style

 

This chapter covers

  • Coding style and standards
  • Using functions to avoid repetitive code
  • Restricting inputs to functions
  • How to implement exception handling in Python
  • Documentation

Using source control to share your code with others is great. In this chapter, we’ll look at how you can make that shared code easy to read, understand, and maintain by exploring a set of practices sometimes referred to as “clean code.” We’ll look at the commonly-accepted standards for Python coding style, some best practices for structuring your code, ways to handle errors gracefully, and some tips for creating good documentation.

3.1 Coding style

When we communicate with each other in spoken or written language, we expect to follow certain conventions of grammar and syntax. Human languages have a form to them that you can hear in our speaking patterns and even recognize visually when we look at printed text. Software developers have settled on similar patterns for programming code, which are often described as coding style. Most programming language communities have formalized style guides that document these expected patterns. For example, in Python, the PEP8 standard defines well-styled Python code. There’s even a set of tools called linters that help you enforce these styles. In this section, we’ll look at PEP8 and the pylint linter.

3.1.1 The PEP8 standard

3.1.2 Using pylint to automatically check the formatting and style of your code

3.1.3 Auto-formatting your code to meet styling guidelines

3.2 Avoiding repetitive code

3.2.1 Replacing missing values in a data frame

3.2.2 Generate metrics for multiple classification models

3.2.3 Avoiding long if-else blocks

3.3 Code modularity

3.3.1 Modularizing your code

3.4 Restricting inputs to functions

3.4.1 Adding type hints to our modularized code

3.5 Clean code, so far

3.6 Handling errors and exceptions

3.6.1 Implementing exception handling

3.6.2 What types of errors can we get in Python?

3.6.3 Using try/except to bypass errors

3.6.4 How to raise errors

3.7 Documentation

3.7.1 Using docstrings