简体   繁体   中英

Import package from adjacent module works in Py2 but not in Py3

I'm still getting used to structuring python projects and relative imports, I thought I understood relative imports mostly until I ran into an issue when testing on Py3.

I have a project that is structure like so:

scriptA.py
package/__init__.py
          scriptB.py
          scriptC.py

and __init.py__ contains the following:

from scriptB import functionB
from scriptC import functionC

In scriptA import package as _package works in Py2.7, but fails on Py3.5 with the error, ImportError: No module named 'scriptB' .

How can I import package in a way that is compatible with both Py2 and 3? Why is this different?

I tried doing import .package as _package but that doesn't seem to change anything (still figuring out when to use . and .. ...

No module named 'scriptB'

Looks like a path error. Check your path statement. The path statement in Windows can be accessed by typing "system" into start menu search bar. From there you can access "Environment Variables", one of which is the "path" statement. There you can see different directories that are allowed to be accessed by Python scripts. Make sure your Python 3.x directory and Python 3.x/scripts directory are listed there.
Files listed in the path statement are kind of like Global Variables in a program. If both Python 2 and Python 3 have the same file names in their directories you could access an incompatible file. I've read that there is a python launcher which will solve this very problem so that you can run multiple versions of python on the same computer. For now I would test to see if this is your problem by -copying the path statement to a backup file and then -remove references to python 2.x, -reboot -run your program. If you want to run multiple versions of python copy the original path statement back and install the python launcher.

So the problem was that the imports in __init__.py should have been relative imports ie:

from .scriptB import functionB
from .scriptC import functionC

I guess this is one of the differences between importing a module and a python package. It seems that in Py3.5 relative imports need to be done explicitly and so an error was thrown. This is my interpretation. unfortunatly the structure I had put in the question was not close enough to the problem I had, so this doesn't solve it... But a more detailed (and probably accurate) answer for this is still welcomed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM