Python context file


Arumoy Shome


July 1, 2020

Python context file for managing imports.

Stolen from The Hitchhiker’s Guide to Python1, I use a file to import python source code located in another directory. This is especially useful for importing source code into test files (which are typically located under the test/ directory for me) and for ipython notebooks (which are typically located under the notebooks directory for me).

  • 1

  • Stick the following snippet in a file in the directory where the source code is required to be imported.
    import os
    import sys
    sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
    import sample

    And in the file where the module need to be imported, stick the following.
    from .context import sample
    Back to top