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?

asked May 26, 2020 at 16:21
4
  • 1
    Does this answer your question? stackoverflow.com/questions/15109548/… Commented May 26, 2020 at 16:25
  • Also this: docs.python.org/2/whatsnew/… Commented May 26, 2020 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 Commented May 26, 2020 at 17:41
  • in folder1/fucntion you can write from main.routine import function1 Commented May 27, 2020 at 1:22

1 Answer 1

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

answered May 26, 2020 at 16:33
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.