Reputation: 78324
I have subfolders A
and B
. I am trying to import a package from sibling A
.
I have __init__.py
in every subfolder and in the root project.
Yet from the file I execute in folder B
I get the below error despite the file being present in folder A
:
Traceback (most recent call last):
File "/home/ubuntu/workspace/cloud-devops/B/ufw_firewall.py", line 5, in <module>
from getparms import *
ImportError: No module named getparms
How to I import my package?
Thanks
Upvotes: 1
Views: 109
Reputation: 10281
Assuming that getparams
is a module and if /home/ubuntu/workspace/
is in your PYTHONPATH
or added via e.g. site
...
import site
site.addsitedir('/home/ubuntu/workspace/')
... you can import in a number of ways:
from cloud_devops.A import getparams
from cloud_devops.A import *
Please note you cannot use cloud-devops
as a module name, which is why I renamed it into cloud_devops
. See more about this in PEP 0008:
Package and Module Names
Modules should have short, all-lowercase names. Underscores can be used in the module name if it improves readability. Python packages should also have short, all-lowercase names, although the use of underscores is discouraged.
...or you could import relatively from the script in B
:
from ..A import getparams
from ..A import *
Two dots means up one package level. Three dots is up two levels, etc.
However, import *
is regarded bad practice, so avoid that if possible. For readability, I would personally always do static imports, not relative ones.
Upvotes: 0
Reputation: 155507
Either use relative imports, from ..A.getparms import *
, or absolute imports from cloud_devops.A.getparms import *
.
You can't just jump from one branch of a tree to another from the leaves without starting from the root or using relative imports.
Upvotes: 1
Reputation: 599778
Adding an __init__.py
doesn't make the modules importable from anywhere; it just means that the directory is a package. You still need to use the package name in your import:
from A import getparms
(Please don't do from x import *
, in any case.)
Upvotes: 0