0

I am trying to learn how to use directories and folders in my code. I tried following this tutorial: https://timothybramlett.com/How_to_create_a_Python_Package_with___init__py.html and then adding on to it. I have tried to create a minimum reproducible code. The folder structure looks like this:

main_folder
├── folder1
│   ├── __init__.py
│   ├── file1.py
│   ├── file1_1.py
├── folder2
│   ├── __init__.py
│   ├── file2.py
├── __init__.py
example1.py

The last init.py looks like this (the other ones inside the folders are empty):

from .folder1.file1_1 import *
from .folder1.file1 import function1
from .folder2.file2 import function2

The idea is that file1 takes in some values from file1_1. file2 calculates some numbers, and both file1 and file 2 is used in the example1 file.

file1_1:

nr = 5

The code in file 1 is:

 from .file1_1 import *


#test that uses the back_function to compute and return in function1
def back_function1(a):
    b = nr + a # a+5
    return b


def function1(a):
    number = back_function1(a)+2 # a + 5 + 2
    print("hello function 1")
    return number 

The code in file 2 is:

def function2():
    print("hello function 2")

In example1 it is this:

import main_folder as m

m.function1(2)
m.function2()

The problem is that when I run example1.py the whole system runs. However, if I try to run only file1 I get the following error:

    from .file1_1 import *
ImportError: attempted relative import with no known parent package

But if I change the from .file1_1 import * to from file1_1 import *, then the opposite happens (I can run file1.py but not example1.py).

How can I fix this?

IdaSB
  • 3
  • 2

1 Answers1

0

If you want to run a submodule you can use the -m flag:

python -m package.subpackage1.moduleX

In your case:

python -m main_folder.folder1.file1

Look at this question for a detailed explanation:

Relative imports for the billionth time

If you really want to just be able to change the script to make it work change your import statement in file 1 to:

if __name__ == "__main__":
    from file1_1 import *
else:
    from .file1_1 import *

It will work but it is not how you would usually structure your python code.

add-IV
  • 66
  • 5
  • I tried running that line of code from the terminal, however I get the following warning: RuntimeWarning: 'main_folder.folder1.file1' found in sys.modules after import of package 'main_folder.folder1', but prior to execution of 'main_folder.folder1.file1'; this may result in unpredictable behaviour warn(RuntimeWarning(msg)). Additionally, I don't understand what I can write in the script (not in the terminal) to make it work? I am sorry I am a bit dense – IdaSB Feb 01 '23 at 19:21
  • @IdaSB I have added a way to do what you want to do but I still recommend you to read the answer I linked earlier. – add-IV Feb 02 '23 at 02:13