import statement

  • Import options for numpy:
    import numpy as np            # Access as np.functionName (USE THIS)
    import numpy                  # Access as numpy.functionName
    import numpy as numnum        # Access as numnum.functionName
    from   numpy import sin, cos  # Access as x=cos(5) or x=sin(5)
    from   numpy import *         # Access as functionName (NEVER DO THIS)
    

Modules

  • You can save code in other files (file.py) and load it into python like you have been doing with libraries.

Create a code file

  • Jupyter's home screen --> New --> text file
  • Save the file as "units.py" at the top
  • Edit the file to have the following code, then save it:
ft_to_m = 1.0/3.28084
m_to_ft = 3.28084
lbm_to_kg = 1.0/2.20462
kg_to_lbm = 2.20462

def K_to_C(T_K):
    return T_K - 278.15
def F_to_C(T_F):
    return (T_F - 32.0)/1.8

Now you can import this file and its variables/functions

In [2]:
import units as u

x_ft = 10
x_m  = x_ft * u.ft_to_m
print(x_m)

T = 212  # F
TC = u.F_to_C(T)
print(TC)
3.047999902464003
100.0

Load certain variables or functions from the module directly

In [6]:
from units import F_to_C

F_to_C(212)
Out[6]:
100.0

The code in the module is run when the module is loaded

  • This allows you to hide boilerplate code in a module and simply import the module.
  • For example, here is the contents of a file called all_imports.py

    import numpy as np
    import matplotlib.pyplot as plt
    import sympy as sp
    import glob
    
  • Now load all of these modules with a simple

from all_imports import *
In [4]:
from all_imports import *

The module you load has to be in the same directory

  • If not, it will search for the modules in directories specified in a system variable PYTHONPATH which you can edit.
  • You can also add the path in python:
    import sys
    sys.path.append('/path/to/folder/with/the/module')
    

dir() function

  • The dir(u) function will show a list of names that module u defines
  • dir(u) will show all currently known names (except builtin names)
In [4]:
dir(u)
Out[4]:
['F_to_C',
 'K_to_C',
 '__builtins__',
 '__cached__',
 '__doc__',
 '__file__',
 '__loader__',
 '__name__',
 '__package__',
 '__spec__',
 'ft_to_m',
 'kg_to_lbm',
 'lbm_to_kg',
 'm_to_ft']
In [ ]: