KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
I know that there are lots of questions about the same import issues in Python but it seems that nobody managed to provide a clear example of correct usage. Let's say that we have a package mypackage with two modules foo and bar . Inside foo we need to be able to access bar . Because we are still developing it, mypackage is not in sys.path . We want to be able to: import mypackage.foo run foo.py as a script and execute the sample usage or tests from the __main__ section. use Python 2.5 How do we have to do the import in foo.py in order to be sure it will work in all these cases. # mypackage/__init__.py ... # mypackage/foo/__init__.py ... # mypackage/bar.py def doBar() print("doBar") # mypackage/foo/foo.py import bar # Fails with module not found import .bar # Fails due to ValueError: Attempted relative import in non-package def doFoo(): print(doBar()) if __name__ == '__main__': doFoo()
Tags (comma-separated)
Save Edits
Cancel