How to properly use relative or absolute imports in Python modules?

You could just start ‘to run the modules as standalones’ in a bit a different way:

Instead of:

python foo/bar.py

Use:

python -mfoo.bar

Of course, the foo/__init__.py file must be present.

Please also note, that you have a circular dependency between foo.py and bar.py – this won’t work. I guess it is just a mistake in your example.

Update: it seems it also works perfectly well to use this as the first line of the foo/bar.py:

#!/usr/bin/python -mfoo.bar

Then you can execute the script directly in POSIX systems.

Leave a Comment