2

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)

3
  • have you tried to print sys.argv in both pythons? Is there any difference? Commented Jul 17, 2019 at 11:19
  • try to rename the inner folder package to something else, and see it it works for both Commented Jul 17, 2019 at 11:20
  • sys.argv worked fine in both versions, it was the relative imports that were the issue @OlvinRoght Commented Jul 17, 2019 at 11:24

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.