1

So i have a structure like this:

main_folder
├── main.py
├── folder1
    ├── function1.py
    └── function2.py
    └── ...
    └── function20.py

and I want to import all the files from folder1 into main.py

It does not work when i write from folder1 import *, but it works when I specifically write from folder1 import function1. Considering I have many scripts under folder1, I would prefer to have them all imported without type each name out. Is there any way to do this (like import *)?

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
raffa
  • 145
  • 2
  • 11
  • 1
    ``from X import *`` only imports names global to ``X``. A submodule ``X.Y`` isn't actually added to ``X`` until imported, and ``from X import *`` won't import submodules. – MisterMiyagi Jul 19 '21 at 14:34
  • what is the right way to import all of them? @MisterMiyagi – raffa Jul 19 '21 at 14:49
  • 2
    I would say "write them all out", but the question seems to exclude that. – MisterMiyagi Jul 19 '21 at 14:56
  • 1
    You could include an `__all__ = ['function1', 'function2', ..., 'function20']` in your `__init__.py` in `folder1` but you still would have to "write them all out" at least once. – Axe319 Jul 19 '21 at 15:03
  • 1
    There is some really hacky stuff you could do like walk through your subdirectory in your `__init__.py`, appending everything to `__all__` that meets the criteria of a submodule but I would not recommend it. – Axe319 Jul 19 '21 at 15:14

1 Answers1

1

List all python (.py) files in the current folder and put them as __all__ variable in __init__.py

from os.path import dirname, basename, isfile, join
import glob
modules = glob.glob(join(dirname(__file__), "*.py"))
__all__ = [ basename(f)[:-3] for f in modules if isfile(f) and not f.endswith('__init__.py')]

Importing * is not a good idea for several reasons, including name clashes and making it hard to analyze the code.

MisterMiyagi
  • 44,374
  • 10
  • 104
  • 119
Jonathan Coletti
  • 448
  • 4
  • 13
  • 2
    Heads up that this won't work if the package is stored inside a zip file or any other structure not on the filesystem. This might need ``importlib`` to do correctly. – MisterMiyagi Jul 19 '21 at 16:28