Modules and Packages

Modules are Python files that have implemented certain functions or constants. They can be very helpful, as you don't have to reinvent the wheel. To use a module, we import it. Below, let's import the math module.


In [1]:
import math

In Jupyter notebooks, once you've imported it, you never need to again. However, in these tutorials I will continously re-import.

Now, how do you use said functions and constants inside of a module? Well, you need to know what's inside first. You can look at Python docs or use the dir() function to help you.


In [4]:
# Using the dir function
print(dir(math))


['__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc']

We now see functions, special functions, and constants that we can manipulate. How do we use, say the log function? Well, you import math, and then use the dot notation to call any of the items that dir directed us to. In this case, we use the math.log, or generally

module.function(....)

to use module constants

module.constant

and so on.


In [6]:
import math
print(math.log(5))


1.6094379124341003

More often than not, you will want to just use the

import module

notation. However, it is often that you might just need one function. We use the

from module import function

for that type of construct. However, this isn't advisable because there can be name conflicts in your own code or perhaps in another module or external library you are using. Thus, we try to use just the import. We don't lose out on performance, generally speaking. Note: We no longer need to specify


In [7]:
from math import log
print(log(5))


1.6094379124341003

Packages

A package is a collection of Python modules - think of it as a directory.

Simply create a directory as normal, and then in there you can make your own modules (.py files with whatever you made). You also need to specify the __init__.py file that specifies the directory is a package directory.


In [ ]:
from directory_name_here import module_name_here