2

I have a module that I pack as an egg with setuptools. I have a problem with relative/absolute improts.

The directory structure is the following:

setup.py        # using setuptools
mymodule/
 |- __init__.py
 |- mymodule_core.py
 |- utils.py

When I easy_install mymodule in the system from egg, this import works well:

# mymodule_core.py
from mymodule.utils import some_functions

But I want also to run mymodule_core.py from the command line, without installing it (for short tests etc). In that case, the previous import would fail, and this works:

# mymodule_core.py
from utils import some_functions

How to handle the import so it would work in both cases?

I guess that the proper solution would include if __name__ == "__main__", from .. import something and __package__ = but I cannot make it work

Related:

Community
  • 1
  • 1
Jakub M.
  • 32,471
  • 48
  • 110
  • 179

1 Answers1

1

One simple way would be to handle the ImportError, like this...

# mymodule_core.py
try:
    from mymodule.utils import some_functions
except ImportError:
    from utils import some_functions

...which would work fine in your case.

For cases where your package structure is such that a 'relative' import won't work, I tend to put something like this at the top of the source 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)))

...then the from packagename.modulename import symbols syntax works either way.

Aya
  • 39,884
  • 6
  • 55
  • 55