0

I have the following structure of my program:

MainDir
├── __init__.py
├── main.py
├── Routine.py
└── Folder1
    ├── __init__.py
    └──function.py

I know that I can import a function from folder 1 to my main.py program writing this statement:

from Folder1.function import foo

But, I am looking for a way to do so in the other direction. How could I import a function defined in Routine.py to function.py?

Erincon
  • 389
  • 1
  • 7
  • 21
  • 1
    Does this answer your question? https://stackoverflow.com/questions/15109548/set-pythonpath-before-import-statements – paltaa May 26 '20 at 16:25
  • Also this: https://docs.python.org/2/whatsnew/2.5.html#pep-328-absolute-and-relative-imports – paltaa May 26 '20 at 16:26
  • The first one worked for me. I imported `os library` to get my current working directory and then appended it to the `sys.path` – Erincon May 26 '20 at 17:41
  • in `folder1/fucntion` you can write `from main.routine import function1` – sahasrara62 May 27 '20 at 01:22

1 Answers1

0

It depends on how you are invoking your program.

Invoking as a module

Do you do something like

python -m MainDir.main

and whatever code is in your MainDir.main calls out to MainDir/Folder1/function.py?

In this case, you can simply add the following import to MainDir/Folder1/function.py:

from ..Routine import RoutineFunction

Invoking as a script

If you are instead invoking MainDir/Folder1/function.py as a script using:

python MainDir/Folder1/function.py

you will not be able to use relative imports as suggested above. There are still many options available to you, as described here: How to import other Python files?

Suggested reading

Python imports can be very confusing. Here is a great post on the topic, which could be useful to you: https://stackoverflow.com/a/14132912/4905625