0

I'm new to Python, and given the following directory structure, I would like to import a function (let's call it function2) from script2 to script1, such that it works on a call in python script1.py and python script.py.

For example: script1 -> calls script2; script -> calls script1 -> calls script2

What would the best way to do that?

I'm getting a lot of confusion about relative/absolute path, and I've seen in some cases __init__.py inside each "package".

root
 ┣  modules
 ┃ ┣  package1
 ┃ ┃ ┗  script1.py
 ┃ ┗  package2
 ┃   ┗  script2.py
 ┗  script.py
Kevin
  • 427
  • 4
  • 12
  • You can use relative paths with `.`, so `from . import something` means "from this folder import the file `something.py`. `from ..something import myfunc` means "from one folder up, from the file something.py, import myfunc". And you need a `__init__.py` file (can be empty) in each folder so python actually looks in them to import stuff. – Swier Dec 09 '20 at 15:22
  • Does this answer your question? [Relative imports for the billionth time](https://stackoverflow.com/questions/14132789/relative-imports-for-the-billionth-time) – Leonardus Chen Dec 09 '20 at 15:24
  • https://docs.python.org/3/tutorial/modules.html#packages is the documentation you are looking for. This documentation will explain all how python packages and modules work and how to import them – Steffen Andersland Dec 09 '20 at 15:24

1 Answers1

0

A package is not what you want (I don't think). If you went and did pip install flask that would install the flask package. This has an __init__.py because that gets all the data you want for the package. It's specially made to be importable with many programs, and more for big projects.

You can have script, script1, and script2 in the same directory using this code (note: this won't work if script1 and script2 are in different directories):

script2:

def outin(prompt):
    print(input(prompt))

script1:

from script2 import outin
def main():
    outin("What is your favorite color: ")

script:

from script1 import main
main()

This will prompt you with What is your favorite color: and then print it out.You can have whatever functions you want in those, it doesn't matter.

Dock
  • 444
  • 5
  • 13