Reputation: 2406
I've got a python package written locally with a structure like
package
├── __init__.py
├── __main__.py
├── tests
│ ├── __init__.py
│ └── package_tests.py
└── package
├── __init__.py
├── package.py
This works great when run using python -m package
in a Python3 virtualenv from the root of the project (parent dir of the first package
dir in that tree)
However when run in a Python2.7 virtualenv, I get an ImportError
in the __main__.py
script as it tries to import the functions from package.py
__main__.py
:
import sys
from package.package.package import foo, bar
def main(args):
f = foo(args)
bar(f)
if __name__ == "__main__":
main(sys.argv[1:])
The error:
ImportError: No module named package
What do I need to change to make it compatible with both?
(Obviously the package isn't actually called package)
Upvotes: 2
Views: 500
Reputation: 2406
Despite looking for an explanation for so long, immediately after posting this question I found a solution.
After looking over the changes to imports between python 2 and 3 I found that I only needed to use relative imports.
So the import line in my __main__.py
became
from .package.package import foo, bar
Upvotes: 1