exp = 'Dear {name}, we would like to express our gratitude for your donation!'
from math import exp
print(exp.format(name="Jeff"))5. Modules, import, pip, testing
Modules and Packages
- A Module is a file containing Python code.
- The Code in the module can be included in your code using the
importcommand - A collection of modules bundled for re-distribution is known as a Package
Built in Modules vs. External
- The Python language has several modules which are included with the base language: Python Standard Library https://docs.python.org/3/library/
- In addition you can import other libraries found on the Internet.
- The Python Package Index is a website which allows you to search for other code avaialbe for use. https://pypi.org/
- Once you know which package you want, you can install it with the
pipcommand from the terminal. - Example:
pip install <name-of-package>(Make sure you activate your conda environment first!) - You can also install packages using conda. For example,
conda install -c conda-forge <name-of-package>. - Which to use? Basically,
condaandpipcan be used interchangeably within a conda environment. Some packages may be in PyPI that are not in conda-forge and vice versa.
Requirements.txt
requirements.txtis a file which stores the names of all the packages a project uses- adding them to the file is a replacement for installing each of them manually
- to install the packages:
pip install -r requirements.txt
Importing Modules
Code in the module can be included in your code using the import command. There are a few different ways to import some code:
import fooimports code from modulefoo. Functions in that module can then be referenced in the current code by prefixing the function withfoo.. For example, iffoohas a functionbardefined in it, then after theimport foostatement you can use thebarfunction by writingfoo.bar(...)(where the...indicate the arguments you need to pass tobar).from foo import bar,bazonly imports thebarandbazfunctions from modulefoo. When imported in this manner, thebarandbazfunctions are referenced directly, without the module prefix. For example, in this case, to execute the bar function, you runbar(...)instead offoo.bar(...).
- Renaming imports: You can avoid namespace collisions by renaming an imported module or functions via:
import foo as f. For example, in the Concept check above, doingfrom math import exp as mathexpwould avoid the error.
Whats in the module?
- Use the
dir(<module>)to list the functions in the module - Use
help(module.function)to get the docstring for a function in a module.
# Examples
import math# get the functions
dir(math)['__doc__',
'__file__',
'__loader__',
'__name__',
'__package__',
'__spec__',
'acos',
'acosh',
'asin',
'asinh',
'atan',
'atan2',
'atanh',
'cbrt',
'ceil',
'comb',
'copysign',
'cos',
'cosh',
'degrees',
'dist',
'e',
'erf',
'erfc',
'exp',
'exp2',
'expm1',
'fabs',
'factorial',
'floor',
'fma',
'fmod',
'frexp',
'fsum',
'gamma',
'gcd',
'hypot',
'inf',
'isclose',
'isfinite',
'isinf',
'isnan',
'isqrt',
'lcm',
'ldexp',
'lgamma',
'log',
'log10',
'log1p',
'log2',
'modf',
'nan',
'nextafter',
'perm',
'pi',
'pow',
'prod',
'radians',
'remainder',
'sin',
'sinh',
'sqrt',
'sumprod',
'tan',
'tanh',
'tau',
'trunc',
'ulp']
help(math.pow)Help on built-in function pow in module math:
pow(x, y, /)
Return x**y (x to the power of y).
math.pow(2,5) # 2*2*2*2*232.0
It’s possible to use a wildcard * when importing. For example,
from math import *will import all functions that are in the math module into the current namespace. This means that you could then call math.pow with just pow, for example.
Don’t do this! The problem with this is you can accidentally override variables in your program without realizing it. For example, if you defined a variable called e then did from math import *, e would be replaced with the value of the natural exponent, since e is defined in the math module. Doing wildcard imports also makes it difficult to debug code, since it’s a challenge to determine what module a particular variable came from. Wildcard imports should only be used in very limited situations, which you are unlikely to run in to. Long story short… don’t use wildcard imports! I only tell you about it in case you see it in the wild (no pun intended).
Testing Your Code
- For every function you write you should get in the habit of writing code to test the function
- We want this to be automated so that we can easily determine if a change to our code has affected other code
- This is especially useful with large projects
Assert
assert is a python command which throws an exception if the expression asserted is false.
When an assert fails, it raises an AssertionError exception which alerts us that something did not go as planned.
assert 1 + 1 == 2 # This is true, no worriesassert 2 + 2 == 5 # False AssertionError--------------------------------------------------------------------------- AssertionError Traceback (most recent call last) Cell In[6], line 1 ----> 1 assert 2 + 2 == 5 # False AssertionError AssertionError:
Pytest
Pytest is testing framework for Python. It can automatically discover tests in your code; for example, any function that starts with test is executed when you invoke pytest. (See here for the full list of rules that pytest uses to discover test functions.)
You can invoke it at the terminal like this:
python -m pytest <filetotest>
Pytest is not installed by default when you create a new conda environment. If you have not installed pytest into your ist356 environment yet, you can do so by opening a terminal and running:
conda activate ist356
pip install pytestThe VS Code test plugin should discover the tests.