0

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.

5
  • Does from commands import * fail? That sounds like it should work. Also: is there an __init__.py file in the commands folder? Commented Sep 24, 2017 at 2:06
  • @JacobIRR that does not fail. Did you read the question? Commented Sep 24, 2017 at 2:07
  • Ah, now I understand. So the modules' inner functions are currently only available by calling somemodule.somefunction() instead of just being able to call somefunction() ? Commented Sep 24, 2017 at 2:08
  • @JacobIRR yes. That is what I am trying to fix, without importing them all one by one Commented Sep 24, 2017 at 2:09
  • You cannot pass a dynamic or evaluated value to an import statement, so I don't think this is possible. Commented Sep 24, 2017 at 2:19

1 Answer 1

1

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 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.