Oliver Oliver
Oliver Oliver

Reputation: 2317

Python import module/function from below subdirectory or anywhere

I would like to load in a function/module with my working directory as project main directory but the function file is store below the a subdirectory level so the normal

from function_file import function_name

does not work.

This is what the project directory set up looks like:

└───project_main_directory
    │   .gitattributes
    │   .gitignore
    │   README.txt
    │
    ├───code
    │   ├───exploration
    │   └───scripts
    │       │   script1.py
    │       │   script2.py
    │       │   script3.py
    │       │
    │       └───functions
    │           │   function1.py
    │           │   function2.py
    │           └───__init__.py
    │
    ├───data
    │   └───example_data
    │           data.csv
    └───documents

So I tried to import functions via

import code.scripts.function.function1 from function1

and that doesn't work. I know it's because the other subdirectories aren't modules, but I want to ask if there is away around that?

-- EDIT I'm working from .py file in code/scripts/script1.py but working directory is project_main_directory/

Upvotes: 1

Views: 726

Answers (3)

Rohit Sinha
Rohit Sinha

Reputation: 1

To import function/module from another python file, you have to do something like below -

from code.scripts.functions.function1 import function1

Above we are loading function1 from function1.py file which is stored in functions directory which is stored in scripts directory and finally in code directory.

EDIT - so you are saying, you want to load a function from function1.py in script1.py? In that case from .functions.function1 import function should work.

Upvotes: 0

Li Jinyao
Li Jinyao

Reputation: 978

Add an empty file __init__.py to every subdirectories to make them as modules.

.
├── code
│   ├── __init__.py
│   └── scripts
│       ├── __init__.py
│       └── script1.py
└── main.py

Then if you have a function called hello in code/scripts/script1.py you can import that function by:

from code.scripts.script1 import hello
hello("yo")

Upvotes: 2

Ankit Malik
Ankit Malik

Reputation: 90

If your current directory is project_main_directory, you can use:

from code.scripts.functions.function1 import function1

Directory of your script doesn't matter. Only your current directory matters (refer top of the IDE)

Upvotes: 0

Related Questions