简体   繁体   中英

How to import module at same directory level?

My project is set up as follows:

/python-tools
  - __init__.py
  - /module_a
    - __init__.py
    - module_a.py
  - /module_b
    - __init__.py
    - module_b.py
  - /common
    - __init__.py
    - common.py

I'm trying to import common.common into module_a.py and module_b.py like this:

from common.common import CommonClass

But I'm receiving ModuleNotFound errors. I've read through the documentation, and as far as I know it should be set up correctly in packages so that these modules could be imported into one another.

Many of the answers online recommend modifying the sys.path to do imports, but that seems absurd to me. I used to work in Python quite a bit and I remember being able to import modules without that hassle.

You need to use leading dots ( .. ) on your imports to move upward in the directory structure.

Here is an example of my structure:

import_test/
├── aspen/
│   └── aspen.py
├── birch/
│   ├── birch.py
│   └── birch_leaf.py
└── common/
    └── common.py

And here are the content of the files, notice that using two leading dots moves up one directory level to within import_test , from there you can access the underlying modules. Also notice you don't need the __init__.py files.

aspen.py

from ..common.common import CommonClass

class AspenClass(CommonClass):
    def root(self):
        print('pain in my aspen!')

Here in the birch directory, we can import from a sibling file using just one dot in the import statement, as in birch_leaf.py below

birch.py

from ..common.common import CommonClass

class BirchClass(CommonClass):
    def root(self):
        print('birch, please!')

birch_leaf.py

from .birch import BirchClass

class BirchLeafClass(BirchClass):
    def fall(self):
        print('i am falling!')

common.py

class CommonClass:
    def __init__(self):
        self.val = None

This set of modules imports and runs using:

from import_test.aspen import aspen
from import_test.birch import birch_leaf

aspen.AspenClass()
birch_leaf.BirchLeafClass()

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