0

How can I take the function to which is located on another file, this is my case: Main folder

I would like to take a function that is located in main.py (the file is in the root folder) and put it in the main.py located in the api folder.

Nathaniel Ford
  • 20,545
  • 20
  • 91
  • 102
  • highlight the function -> right click -> copy -> right click in the other file -> paste, python will specifically raise an error when you try to import it using the basic import statement because it clearly belongs in the subfolder file, not the file in the root, and the fact you are importing something in the submodule from the root module is clearly bad design. – Ahmed AEK Aug 18 '22 at 16:19

1 Answers1

0

Inside api/main.py, you can use leading dots to specify how many folders up you should go. 1 dot means "stay in this folder", 2 dots "go up 1 folder", 3 dots "go up 2 folders", and so on. So in your case, inside api/main.py you'd do

from ..main import the_function_you_want_to_import

However, keep in mind that if you plan to run api/main.py directly, Python will complain that you can only do relative imports (that's with the dots that I just mentioned) in package files, which your api/main.py automatically cannot be because you're running it.

On top of that, if you plan to run main.py (the root one), then it will most likely not be possible for api/main.py to import things from your root main.py, since that would cause a circular import, which is not allowed in Python.

Artie Vandelay
  • 436
  • 2
  • 10
  • isn't that sibling import, that would raise an error. – Ahmed AEK Aug 18 '22 at 16:09
  • @Ahmed AEK Yeah, I updated my answer, because if you're trying to import stuff from your main file, or you're trying to run a file which imports things from parent folders, you're most likely doing something wrong. – Artie Vandelay Aug 18 '22 at 16:10