Home > Software design >  Importing python function from outside of the current folder
Importing python function from outside of the current folder

Time:05-17

enter image description here

I have this directory structure. The code inside utils.py is:

def hello():
    print("hello")

The code inside run.py is:

from ..helper.utils import hello

hello()

Using this setting, I'm getting the error:

    from ..helper.utils import hello
ImportError: attempted relative import with no known parent package

I know there exist a solution using sys.path.append(), however it'll be better if there exist a solution without using this.

CodePudding user response:

The reason that the current solution is not working is that Python cannot perform relative imports across multiple directories at the same level in the project hierarchy, so in this case between mains/ and /helper/. In order to make this work the search path which Python uses to find packages needs to include the helper/ directory.

There are 3 ways to handle this issue: running from a directory up in the terminal, using sys.path, using PYTHONPATH.

i) running from a directory up in the terminal will solve the problem because it will change the root directory for the scripts being executed. So, instead of running the script directory - for example, from an IDE - you would need to go to navigate to a higher directory and execute the script using the terminal. For example, were you to be in the src/ directory you could execute the script using the following code:

python mains/run.py

ii) Updating sys.path solves the problem because it adds another directory to the search path which Python uses so that the helper/ directory can be found. It can be updated using the following code:

import os
import sys

rootpath = os.path.join(os.getcwd(), '..')
sys.path.append(rootpath)

This adds the directory above mains/ to the search path and lets you import from helper/.

iii) In place of the second option above you can also update the PYTHONPATH to include the directory which you want to search, i.e. the same directory that was added to sys.path above.

Please note that you will need to import using from helper.utils import hello when using these solutions. Because the search path has been updated you are not performing a relative import - Python is looking in the directories that you've added and the imports are below them in the hierarchy.

CodePudding user response:

just do this : from helper.utils import hello

And check :Call a function from another file?

  • Related