It is a method to store Plugin etc. in a certain directory and import all the * .py files in that directory without specifying the file individually in the code.
Assume the following directory structure.
./loader.py
./plugins
./plugins/__init__.py
./plugins/a.py
./plugins/b.py
__init__.py
is empty and OK. ʻA.pyand
b.py` look like this for the time being.
a.py
#!/usr/bin/env python
# coding: utf-8
class Plugin1:
''' plugin1 '''
class Plugin2:
''' plugin2 '''
b.py
#!/usr/bin/env python
# coding: utf-8
class Plugin3:
''' plugin3 '''
Write loader.py
as follows.
loader.py
#!/usr/bin/env python
# coding: utf-8
import os
import inspect
import importlib
import glob
def load_classes(dname):
class_list = []
# *.Load py
for fpath in glob.glob(os.path.join(dname, '*.py')):
#Remove extension & file path separator(Unix'/')To'.'Replace with
cpath = os.path.splitext(fpath)[0].replace(os.path.sep, '.')
#Load as a module
mod = importlib.import_module(cpath)
#Call the class included in the loaded module
for cls_name, cls in inspect.getmembers(mod, inspect.isclass):
# (Class name including directory path,Class body)Stored in the format
class_list.append(('{0}.{1}'.format(cpath, cls_name), cls))
return class_list
import pprint
clist = load_classes('plugins')
pprint.pprint(clist)
The execution result is as follows.
$ ./loader.py
[('plugins.a.Plugin1', <class plugins.a.Plugin1 at 0x10d2538d8>),
('plugins.a.Plugin2', <class plugins.a.Plugin2 at 0x10d253940>),
('plugins.b.Plugin3', <class plugins.b.Plugin3 at 0x10d2539a8>)]
The second element of the list is the class body, which you can use to instantiate.
c = clist[0][1]()
print c
# <plugins.a.Plugin1 instance at 0x107195d40>
Recommended Posts