Qwerty
Qwerty

Reputation: 1267

Python modules import *

I have a folder of modules called commands.

these modules each have a unique named function in them.

From the main directory, the one with the commands folder, I have a main.py

I can import all the modules with from commands import *

Is there a way to import all the functions inside all the modules without importing them individually. Even using a for loop would be fine.

Upvotes: 0

Views: 44

Answers (1)

mshsayem
mshsayem

Reputation: 18008

Assuming you have a directory which have some python files (.py) and a main.py (inside the same directory) into which you want all functions of other files to be available. Here is a naive approach (a bad idea, really), and of course, watch out for name collisions:

Inside main.py:

from os import listdir
from importlib import import_module

for file in listdir('.'):   
    if file.endswith('.py') and file not in __file__:
        module_name = file[:file.index('.py')]
        # if you want all functions to just this file (main.py) use locals(); if you want the caller of main.py to have access, use globals()
        globals().update(import_module(module_name).__dict__)

# Functions defined in all other .py files are available here

Upvotes: 1

Related Questions