Python Imports: Reference and Examples

Python Imports: Reference and Examples

Last updated:
Table of Contents

WIP Alert This is a work in progress. Current information is correct but more content may be added in the future.

Examples use Python 3+ unless otherwise stated!

Import from path/directory

To import from a relative path instead see below: Import from relative path

To import modules, variables and functions from custom python files placed in a directory you need to: 1) add that directory to the import path and then 2) import from files.

  • Example import from myfile.py, located under /absolute/path/to/directory":

    import sys
    
    # add directory to import path
    sys.path.insert(0, "/absolute/path/to/directory")
    
    # import from python modules/files below directory
    from myfile import somefunc
    

Import from relative path

Similar to the above but get path with os.path.abspath(<relative-path>) and then use sys.path.insert(0, <path>) so that you can import from a relative directory:

Example

  • Directory structure:

    myproject/
    ├── helpers
    │   └── mymodule.py
    ├── utils
    │   └── myothermodule.py
    └── stuff
        └── file1.py
    
  • import stuff in file1.py

    # stuff/file1.py
    import os
    import sys
    
    # find out the absolute path to the directory
    # you want to add to your path
    path_to_myproject = os.path.abspath(__file__+"/../")
    
    sys.path.insert(0, path_to_myproject)
    
    # now you can import stuff like this
    from helpers import mymodule
    from utils import myothermodule
    

Add directory to import path

See Import from directory above to see how to use it

Use sys.path.insert(0,"/absolute/path/to/directory")

import sys

sys.path.insert(0, "/absolute/path/to/directory")

Add relative path to import path

See Import from relative path above to see how to use it

Similar to the above but get path with os.path.abspath(<relative-path>) and then use sys.path.insert(0, <path>):

Use sys.path.insert(0,"/absolute/path/to/directory")

import os
import sys

# turn relative to absolute path
absolute_path = os.path.abspath(__file__+"/../")

# and add it to import path
sys.path.insert(0, absolute_path)

Sys.path.insert example

See above: Add directory to import path

Dialogue & Discussion