Chapter 4. Code Reuse: Functions and Modules

Reusing code is key to building a maintainable system.
And when it comes to reusing code in Python, it all starts and ends with the humble function. Take some lines of code, give them a name, and you’ve got a function (which can be reused). Take a collection of functions and package them as a file, and you’ve got a module (which can also be reused). It’s true what they say: it’s good to share, and by the end of this chapter, you’ll be well on your way to sharing and reusing your code, thanks to an understanding of how Python’s functions and modules work.
Reusing Code with Functions
Although a few lines of code can accomplish a lot in Python, sooner or later you’re going to find your program’s codebase is growing...and, when it does, things quickly become harder to manage. What started out as 20 lines of Python code has somehow ballooned to 500 lines or more! When this happens, it’s time to start thinking about what strategies you can use to reduce the complexity of your codebase.
Like many other programming languages, Python supports modularity, in that you can break large chunks of code into smaller, more manageable pieces. You do this by creating functions, which you can think of as named chunks of code. Recall this diagram from Chapter 1, which shows the relationship between functions, modules, and the standard library:
In this chapter, we’re ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access