1

I have python scripts in a structure like this:

Folder:
    -main.py
    SubFolder:
        -file1.py
        -file2.py
        -filen.py
        -__init__.py

file1 has a module lets call it "module1()" and a variable "variable1".

file2 has "module2()" and "variable2" etc

So far, and it works perfectly, I used this way:

in main:

from subFolder import file1, file2
file1.module1()
file2.module2(file1.variable1)

file1.variable1

But since there are many files in the subFolder, I would like to make it more clean and elegant. I tried writing in the init.py file this

from file1 import module1
from file2 import module2
etc

And then in the main:

 import subFolder as sf
 sf.module1()
 sf.module2(sf.variable1)  <--

which seems to work correctly for the modules, but not for the variables(indicated by the arrow). What should I do? Am I doing something wrong? Thanks in advance

Joe
  • 12,057
  • 5
  • 39
  • 55

1 Answers1

0

You need to import it explicitly but since you mentioned that you have a lot of modules in your package “SubFolder” I will suggest you utilize dunder __all__ So you could type:

from subFolder import *

And it will import everything that you will specify in __all__ inside your __init__.py.

See answer by @alec-thomas here for more details and examples.

Pros:

  • No need to specify every module, function or variable explicitly.
  • One import bring you everything you need.

Cons:

  • You will have to remember to update __all__ every time you add, rename or delete stuff in your sub-modules.
  • Over time once you a have a lot of sub-modules it becomes unclear what exactly will be imported.
kuza
  • 2,761
  • 3
  • 22
  • 56