I am new to Python and I am trying to understand a problem, which I see when creating a package. I have the following file structure: (Working-Directory is /my/Python/jmLib2)
/my/Python/jmLib2 |--- Phone | |--- __init__.py | |--- Pots.py |- Test2.py --------------------------------- cat ./jmLib2/Pots.py #!/usr/bin/python def Pots(): print ("I'm Pots Phone") --------------------------------- cat ./jmLib2/__init__.py from Pots import Pots --------------------------------- cat ./Test2.py #!/usr/bin/python from Phone import Pots import os.path print ("OS:"+str(os.path)) Pots()
When I now do:
python2 Test2.py OS:<module 'posixpath' from '/usr/lib/python2.7/posixpath.pyc'> I'm Pots Phone*
GREAT...BUT, if I do:
python3 Test2.py Traceback (most recent call last): File "Test2.py", line 2, in <module> from Phone import Pots File "/home/juergen/my/Python/jmLib2/Phone/__init__.py", line 1, in <module> from Pots import Pots ImportError: No module named 'Pots'
I am working with PyDev under Eclipse. PyDev reports me inside the init.py file an "Unresolved import: Pots"-error. I have the same traceback-problem under PyDev and bash.
Again, I am new to Python... so it is maybe a very stupid mistake. But can someone explain me, the difference between python2 and python3.4? Do I have to modify the PYTHONPATH? Why?
Greetings Juergen
To get rid of this error “ImportError: No module named”, you just need to create __init__.py in the appropriate directory and everything will work fine.
Python's ImportError ( ModuleNotFoundError ) indicates that you tried to import a module that Python doesn't find. It can usually be eliminated by adding a file named __init__.py to the directory and then adding this directory to $PYTHONPATH .
TL;DR: Relative imports are gone. Use absolute imports instead.
Either use:
from Phone.Pots import Pots
or:
from .Pots import Pots
The problem occurs because Pots
is part of the Phone
package: there is no module named Pots
, there's a module named Phone.Pots
.
Python 2 had a feature called relative imports that let you write import Pots
even if that was not technically correct.
Relative imports however are a source of problems and confusion:
Phone.Pots
, but I can use import Pots
? This is highly inconsistent.For these reasons, relative imports were removed from Python 3.
You can get rid of relative imports from Python 2 by using a __future__
import:
from __future__ import absolute_import
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