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.