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).
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With