How can I autoload all my modules that kept in different directories and sub directories?
I have seen this answer which is using __import__
, but it is still not the autoload that I have in mind.
I'm thinking something similar to PHP autoloader. Even better something like Composer autoloader.
It seems that autoloader is not a popular thing in Python from the research I have gathered so far (can't be sure as I'm new in Python). Is autoloading something not encourage-able in Python?
My autoload code so far,
import os
import sys
root = os.path.dirname(__file__)
sys.path.append(root + "/modules")
sys.path.append(root + "/modules/User")
sys.path.append(root + "/modules/Article")
# IMPORTS MODULES
module = __import__("HelloWorld")
my_class = getattr(module, "HelloWorld")
# This is our application object. It could have any name,
# except when using mod_wsgi where it must be "application"
def application(environ, start_response):
results = []
helloWorld = my_class()
results.append(helloWorld.sayHello())
output = "<br/>".join(results)
print output
...
As you can see that I still need to have these lines in order to load the modules,
sys.path.append(root + "/modules")
sys.path.append(root + "/modules/User")
sys.path.append(root + "/modules/Article")
What if I have tons of folders and sub folders? Am I going to list them all? It is going to a long list eventually, isn't?
Also, using __import__
seems does not make much of difference from this,
import os
import sys
root = os.path.dirname(__file__)
sys.path.append(root + "/modules")
sys.path.append(root + "/modules/User")
sys.path.append(root + "/modules/Article")
# IMPORTS MODULES
import hello
import HelloWorld
from HelloWorld import HelloWorld
# This is our application object. It could have any name,
# except when using mod_wsgi where it must be "application"
def application(environ, start_response):
The latter looks nicer and neater to me.
Any ideas?