Chapter 7. Modules in Python
A module is a file containing Python definitions and statements.
In this chapter, we’ll do a few things to improve the organization of our Python code. We’ll separate our test code from our production code using modules. We’ll see how the scoping and import rules in Python help us ensure the dependencies in our code are correct. Finally, we’ll remove a redundant test from our code, making things compact and meaningful.
Separating Our Code into Modules
We have production code for Money and Portfolio right next to our test code in the same file. We need to separate this code into individual source files.
Let’s first create two new files named money.py and portfolio.py in the same folder as test_money.py. Our folder structure looks like this:
py ├── money.py ├── portfolio.py └── test_money.py
We move the code for Money and Portfolio classes to money.py and portfolio.py, respectively. This code segment shows the complete contents of portfolio.py after this code relocation:
importfunctoolsimportoperatorclassPortfolio:def__init__(self):self.moneys=[]defadd(self,*moneys):self.moneys.extend(moneys)defevaluate(self,currency):total=functools.reduce(operator.add,map(lambdam:m.amount,self.moneys),0)returnMoney(total,currency)
Notice that we carry the two import statements along with the code for the Portfolio class, because Portfolio uses functools and operator.
The file money.py, not shown here, similarly contains ...
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