Skip to content

Instantly share code, notes, and snippets.

@osule
Created July 11, 2016 09:00
Show Gist options
  • Save osule/0f1e4b08d9470bd7da80325e4c16dce1 to your computer and use it in GitHub Desktop.
Save osule/0f1e4b08d9470bd7da80325e4c16dce1 to your computer and use it in GitHub Desktop.
How to python packages

Setting up custom python packages

I know of one or more reported cases where python imports failed. Because python packages are arranged with reference to the file system structure, running a module that imports a package that is one-level up in the file hierarchy results in an ImportError.

This error can be resolved in any of the following ways:

  1. Export $PYTHONPATH variable in your terminal

    export PYTHONPATH=.

    Check out this Enthought article about other alternatives.

  2. Programmatically append the module's base path to sys.path

    import sys
    
    sys.path.append('./../')
  3. Use Path entry finders ✔️

    While rambling about trying to run a module that imports a name from another module, I came upon a documentation about Path entry finders in the packages section of python docs

    Simply set __path__ to a list or tuple of paths where python can lookup modules.

    For my example package in this repository, I set __path__ = ['./../'] in the module I that intend to run.

    python3 one/b.py
    two

See an example package on using Path entry finders

@kosyfrances
Copy link

kosyfrances commented Jul 11, 2016

Thanks. This helps.
Just to add to what you have from what I found on stackoverflow, If you just want to run the file, you could run it with the -m flag.

Python3 -m package.file.py

or you can add this at the top of the file

import sys
import os

 PACKAGE_PARENT = '..'
 SCRIPT_DIR = os.path.dirname(os.path.realpath(os.path.join(os.getcwd(), os.path.expanduser(__file__))))
 sys.path.append(os.path.normpath(os.path.join(SCRIPT_DIR, PACKAGE_PARENT)))

or just add this

import sys
sys.path.append('.')

This also has some useful tip, I have not tried it yet though, using a main.py file at the root of the project. https://docs.python.org/3/library/__main__.html

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment