Different Ways to Import Modules

You may import modules in several ways as described below. I'm not sure if these methods are synonymous or if there is one preferred over the others. I had used all three ways and simply want to document these options.

Pre-requisite:

Make the call to sys.path.append

In [1]:
'''
import from a different directory
'''
import sys, os
sys.path.append(os.path.abspath("/Users/ghb/Dropbox/Public/workspace/ghb.python"))
from utils import ghbutils_v2 as gb
utils01 = gb.ghbutils_v2()
utils01.print_version()
Using ghbutils version 0.2.6

OR you can do it this way

Pre-requisite:

Import the imp module

In [2]:
#OR
'''
import from a different directory
'''
import imp
# the first parameter needs to be 'ghbutils_v2', cannot use any name
ghbutils = imp.load_source('ghbutils_v2','/Users/ghb/Dropbox/Public/workspace/ghb.python/utils/ghbutils_v2.py')
utils02 = ghbutils.ghbutils_v2()
utils02.print_version()
Using ghbutils version 0.2.6

OR you can do it this way

Pre-requisite:

The PYTHONPATH variable needs to be setup properly for Jupyter. If you have a venv you have to pay attention to your setup (activate and deactivate).

In [3]:
from utils import ghbutils_v2 as gb
utils03 = gb.ghbutils_v2()
utils03.print_version()
Using ghbutils version 0.2.6