0
votes

I'm inside a python package where there is A.py, B.py and an init file that allows me to import packages into the directory above.

Thus, the content of my init file is as follows:

__path__ = __import__('pkgutil').extend_path(__path__, __name__)

I now want to import a class of B.py into A.py. I tried to use from B import myClass but it doesn't work. I also tried to add the file in the path by adding this line to the init file :

__path__.append(__file__)

How to add B.py to the path ?

--edit--

To clarify things, here is the structure of my packages and modules :

|app.py 
|package1
    |__init__.py
    |C.py
    |package2
        |__init__.py
        |A.py
        |B.py

In A.py I need to import classes from B.py and C.py

1
Can you please edit your question to show the layout of your files? What do you mean by "import packages into the directory above"? It is not entirely clear what you are trying to do. Is there a reason why you don't use relative imports, i.e. from .B import myClass (note the .)?MisterMiyagi
I just edited my question. Is that clearer?Rig0L
Yes, that makes it clearer indeed. Can you still please clarify why you don't use relative imports, such as from .B import myClass and from ..C import myClass?MisterMiyagi
Yes, it's working with from .B import myClassRig0L

1 Answers

0
votes

If this is python 3 related code...then really there's no need for an __init__.py anymore.

As long as your files that you want to import classes/functions from are within the same directory you should be able to just call in the file you want to do the import as this:

 import B.myClass

or,

 from . import myClass
 ### this imports all the classes and moduels from within the same directory 
 ### as you're currently in even if it has more than one file (but only imports myClass)