Relative Imports in a Python Script
Have you ever attempted a relative import in a Python script?
$ ./foo/bar/script.py some parameters Traceback (most recent call last): File "foo/bar/script.py", line 16, in <module> from .quux import find_vcs ValueError: Attempted relative import in non-package
I prefer to use absolute imports to minimize ambiguity and confusion, and most of my Python modules begin with:
from __future__ import absolute_import, unicode_literals, print_function
(Using unicode_literals and print_function makes porting to Python 3 easier.)
I recently read the accepted answer to Python relative imports for the billionth time and the solution to the above ValueError occurred to me: Use python -m package instead:
$ python -m foo.bar.script some parameters
(Assuming that package foo exists.)
blog comments powered by Disqus