How to read all the classes contained in * .py in the directory specified by Python

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.pyandb.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

How to read all the classes contained in * .py in the directory specified by Python
How to know the current directory in Python in Blender
How to switch the configuration file to be read by Python
How to use the asterisk (*) in Python. Maybe this is all? ..
Read the file line by line in Python
Read the file line by line in Python
[Python] Read the specified line in the file
How to sort by specifying a column in the Python Numpy array.
How to use the C library in Python
How to erase the characters output by Python
How to get the files in the [Python] folder
How to read a file in a different directory
How to get a list of files in the same directory with python
How to get the variable name itself in python
How to get the number of digits in Python
[Reintroduction to python] How to import via the parent directory
Read the xml file by referring to the Python tutorial
How to use the model learned in Lobe in Python
[Python] How to output the list values in order
How to read csv containing only integers in Python
How to list files under the specified directory in a list (multiple conditions / subdirectory search)
How to develop in Python
[python] How to check if the Key exists in the dictionary
[Python] Open the csv file in the folder specified by pandas
How to debug the Python standard library in Visual Studio
How to use the __call__ method in a Python class
How to get the last (last) value in a list in Python
How to get all the keys and values in the dictionary
How to read text by standard input or file name specification like cat in Python
Python> library> os> os.walk ()> Get directory structure / Implementation to get each file path in the specified directory
How to check if the contents of the dictionary are the same in Python by hash value
How to use classes in Theano
How to collect images in Python
How to use SQLite in Python
In the python command python points to python3.8
How to read the SNLI dataset
How to get the Python version
[Python] How to import the library
How to use Mysql in python
How to wrap C in Python
How to use ChemSpider in Python
How to use PubChem in Python
How to handle Japanese in Python
How to determine the existence of a selenium element in Python
How to get all the possible values in a regular expression
The 15th offline real-time how to write reference problem in Python
The 17th Offline Real-time How to Solve Writing Problems in Python
How to check the memory size of a variable in Python
How to judge that the cross key is input in Python3
Read the standard output of a subprocess line by line in Python
[Introduction to Python] How to use the in operator in a for statement?
How to check the memory size of a dictionary in Python
The 14th offline real-time how to write reference problem in python
How to delete multiple specified positions (indexes) in a Python list
[Beginner memo] How to specify the library reading path in Python
The 18th offline real-time how to write reference problem in Python
How to display bytes in the same way in Java and Python
[Python Kivy] How to get the file path by dragging and dropping
[Introduction to Python] How to use class in Python?
The 17th offline real-time how to write reference problem implemented in Python
How to read pydoc on python interpreter