-2

I've been looking around this site for how I can import a class stored in a folder at the same hierarchy level. What I found is that using .. should bring me up one folder. Or at least, that is how I read it as that assumption seems to be wrong.

src/
    folderStrucutre1/
        __init__.py
        fileToImport.py <- contains A
    folderStrucutre2/
        someFile.py
        __init__.py
abc.py

Having above folder structure in which fileToImport.py contains a class named A. How would I import A into someFile.py?

SomeDutchGuy
  • 2,249
  • 4
  • 16
  • 42
  • Maybe `import ..folderStructure1.fileToImport`? – xkcdjerry Jan 28 '21 at 08:39
  • Does this answer your question? [How does python library handle internal imports?](https://stackoverflow.com/questions/53863776/how-does-python-library-handle-internal-imports/53864451#53864451) – MisterMiyagi Jan 28 '21 at 09:27

3 Answers3

1

Due to how packages work in python, you need to move src and abc.py into a subfolder, and provide an __init__.py for it.

The directory structure should look like this after the changes:

package-name/
    package-name/
        folderStructure1/
            __init__.py
            fileToImport.py <- contains A
        folderStructure2/
            __init__.py
            someFile.py
    __init__.py
    abc.py

Then, in someFile.py you can import A using a relative import from the parent package:

from ..folderStructure1.fileToImport import A

Lastly, you should open the topmost folder (parent to abc.py) for IDE intellisense to work

JoshuaMK
  • 104
  • 1
  • 6
  • This gives: Attempted relative import beyond top-level package, in Intellisense. – SomeDutchGuy Jan 28 '21 at 08:46
  • did you add a `__init__.py` file alongside `abc.py`? I realized I forgot to add it in the example structure, so if you didn't add one because of that it's my bad :P I edited the diagram to include `__init__.py` for future reference – JoshuaMK Jan 28 '21 at 08:53
0

First, we need to create the absolute path to your src folder without hard-coding it in your script to make it portable.

Add this code in your someFile.py file.

import os
src_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

Now, let's add your folderStructure1 directory to the Python Search Path

import sys
sys.path.append(src_path + '/folderStructure1')

Now you can use the following:

from fileToImport import Class
object = Class()
alexandrosangeli
  • 262
  • 2
  • 13
-1

You can add src to the python search path and then you can import A from fileToImport.py.
For this, you should write someFile.py like:

import sys
sys.path.append("..")   # .. represente the father folder

from folderStrucutre1.fileToImport import A

instance_for_A = A()
Pierre
  • 81
  • 4