Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Usage of relative imports in Python has one drawback, you will not be able to run the modules as standalones anymore because you will get an exception: ValueError: Attempted relative import in non-package

# /test.py: just a sample file importing foo module import foo ...  # /foo/foo.py: from . import bar ... if __name__ == "__main__":    pass  # /foo/bar.py: a submodule of foo, used by foo.py from . import foo ... if __name__ == "__main__":    pass 

How should I modify the sample code in order to be able to execute all: test.py, foo.py and bar.py

I'm looking for a solution that works with python 2.6+ (including 3.x).

like image 665
sorin Avatar asked Sep 01 '10 10:09

sorin


People also ask

Should I use relative or absolute imports Python?

With your new skills, you can confidently import packages and modules from the Python standard library, third party packages, and your own local packages. Remember that you should generally opt for absolute imports over relative ones, unless the path is complex and would make the statement too long.

What is correct way to import a Python module?

Importing Modules To make use of the functions in a module, you'll need to import the module with an import statement. An import statement is made up of the import keyword along with the name of the module. In a Python file, this will be declared at the top of the code, under any shebang lines or general comments.


1 Answers

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.

like image 106
Jacek Konieczny Avatar answered Oct 13 '22 18:10

Jacek Konieczny