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:
import
functools
import
operator
class
Portfolio
:
def
__init__
(
self
):
self
.
moneys
=
[]
def
add
(
self
,
*
moneys
):
self
.
moneys
.
extend
(
moneys
)
def
evaluate
(
self
,
currency
):
total
=
functools
.
reduce
(
operator
.
add
,
map
(
lambda
m
:
m
.
amount
,
self
.
moneys
),
0
)
return
Money
(
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 ...
Get Learning Test-Driven Development now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.