George V. Reilly

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 uni­code_lit­er­als and print­_­func­tion 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
Installing Python 2.7.11 on Ubuntu » « Federal Holidays Inadequately Observed