Python 1-4#
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
importcommandA 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>
Requirements.txt#
requirements.txtis a file which stores the names of all the packages a project usesadding 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.
import fooimports all code from modulefoofrom foo import bar,bazonly imports thebarandbazfunctions from modulefooimport foo as fimports all code from modulefooand renames it tof(usually to avoid naming conflicts)
Whats in the module?#
Use the
dir(<module>)to list the functions in the moduleUse
help(module.function)to get the docstring for a function in a module.
1# Examples
2import math
1# get the functions
2dir(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',
'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',
'tan',
'tanh',
'tau',
'trunc',
'ulp']
1help(math.pow)
Help on built-in function pow in module math:
pow(x, y, /)
Return x**y (x to the power of y).
1math.pow(2,5) # 2*2*2*2*2
32.0
Challenge 1-4-1#
use the datetime module to:
parse a string like this “Month/Day/Year” 1/15/2025 into a datetime then print it like this: YYYY-MM-DD
For example in the current date is January 15, 2025 the output should be 2025-01-15
You will need to read through the module with dir() and help() or read the python docs to determine which functions to use.
Challenge 1-4-2#
Let’s make the code in 1-4-1 more resusable
re-write the date parse into a function parsedate_mdy(text: str) -> datetime:
re-write the date format into a function formatdate_ymd(date: datetime) -> str:
re-write the main program to use both functions. input -> parsedate -> formatdate -> output
Challenge 1-4-3#
Let’s make the code in 1-4-2 more resusable!!!
move your functions into a module names dateutils.py
import your functions from dateutils.py into 1-4-3.py
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.
1assert 1 + 1 == 2 # This is true, no worries
1assert 2 + 2 == 5 # False AssertionError
---------------------------------------------------------------------------
AssertionError Traceback (most recent call last)
Cell In[11], line 1
----> 1 assert 2 + 2 == 5 # False AssertionError
AssertionError:
Pytest#
Pytest is testing framework for Python.
https://docs.pytest.org/en/stable/index.html
Pytest can automatically discover tests in your code. Any function that contains an assert will be executed when you invoke pytest.
You can invoke it at the terminal like this:
python -m pytest <filetotest>
The VS Code test plyugin should discover the tests
Challenge 1-4-4#
Automated testing for our module in 1-4-3
write two functions test_parsedate_mdy() and test_formatdate_ymd()in dateutils.py to test each of the two functions. Write two asserts for each function
Run pytest or VS Code test to make sure your tests pass!