Structuring Python
Programs
Testing Python
Programs
The Python import system can be used for:
Import an entire module from the standard library:
Note the namespacing, “random.randint()”
Import one part of a module without namespacing:
The randint() function is now in top-level scope.
Import a function or class under a different name:
“rand” becomes an alias for random.randint()
Modules outside the standard library must be installed:
>>> import pandas
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'pandas'
Unless it is installed on your system, pandas is not available.
You can use pip/pip3 (Python Package Manager) to install non-standard modules:
$ pip3 install pandas
Collecting pandas
... lots of lines ...
Installing collected packages: ...
Successfully installed ... pandas-0.23.4 ...
Anyone who wants to run your code must similarly install pandas. This is known as a dependency.
Imagine you have a module called petshop.py that depends on pets.py, which includes two classes (Cat and Dog).
By importing “pets”, the classes in pets.py become available in petshop.py.
During imports, Python searches the following:
Imagine a function designed to draw a triangle. You might create an assert statement to check that the interior angles add up to 180°:
assert len(angles) == 3, ‘must have 3 angles’
The second (incorrect) assertion raises an error
Imagine a function designed to evaluate whether or not a number is prime: