简体   繁体   中英

Why can't I import package from sibling directory in python even with use of __init__.py?

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

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.

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.)

Assuming that getparams is a module and if /home/ubuntu/workspace/ is in your PYTHONPATH or added via eg 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.

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