2

Here's my file hierarchy:

|--main.py
|--package/
 |--__init__.py
 |--a.py
 |--b.py

Now what I'd like to do is something like this:

# main.py
from package import *
print(package.a.MyClass)
print(package.b.my_function)

So basically I want it to automatically import everything that's inside the package package. Is this possible? I would rather not have to write the imports manually, as I want it to be "drag&drop your files here and you're done" kind of system.

asked Apr 24, 2015 at 9:54

1 Answer 1

2

I recommend using Python's pkgutil.iter_modules

Example:

import pkgutil
for module_loader, name, ispkg in pkgutil.iter_modules(["/path/to/module"]):
 ...

What you do with the iterated sub-modules is up to the user.

An alternative and commonly used approach is to use pkg_resources which you can also look into and I believe comes as part of setuptools

Update: The naive approach to this is to use __import__ and os.lsitdir():

import os
def load_modules(pkg):
 for filename in os.listdir(os.path.dirname(pkg.__file__)):
 if filename.endswith(".py"):
 m = __import__("{}.{}".format(pkg.__name__, os.path.splitext(filename)[0]))

NB: This is not tested but should give you a rough idea.

answered Apr 24, 2015 at 9:57
Sign up to request clarification or add additional context in comments.

2 Comments

How would I import them from here, if that's all I need to do? Use __import__(name) in the for loop?
Yeah pretty much. Probably a little more work though :) There are many approaches to this.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.