简体   繁体   中英

How do I dynamically create instances of all classes in a directory with python?

I'm trying to do something like this:

from A.AA import Q, W
from A.AB import E
from A.B.ABA import R
from A.B.ABB import T, Y, U

objs = []
objs.append(Q())
objs.append(W())
objs.append(E())
objs.append(R())
objs.append(T())
# and so on...

The above code is very large, and would take up a bunch of unnecessary time to update it every time I add a new class or module. Instead, I would like a way to dynamically initialize an object from each of the classes within a directory and all nested directories. Something that would abstract down to the following.

objs = []
for py_file in directory:
    for class in py_file:
        objs.append(construct_object_of_type(class))

As a side note, all of those classes inherit from a single base class. This code would also be called from a python file in the top level directory.

If you want to instantiate all the imported objects, you can access them through the global name space with global() built-in function.

from A.AA import Q, W
from A.AB import E
from A.B.ABA import R
from A.B.ABB import T, Y, U

instances = [obj() for name, obj in globals().items() if not name.startswith('__')]

Also note that basically creating all the instances at once is not a good idea, one reason is that you may don't want to use all of them all ways, and another one might be the problem with passing the specific arguments to constructors for each (or some) class, or if you have some imported objects that you don't want to instantiate, then have to take care of them too, and another problems as well.

So I managed to figure out how to do this.

Here's the code for it:

import os
import imp
import inspect

obj_list = []

dir_path = os.path.dirname(os.path.realpath(__file__))
pattern = "*.py"

for path, subdirs, files in os.walk(dir_path):
    for name in files:
        if fnmatch(name, pattern):
            found_module = imp.find_module(name[:-3], [path])
            module = imp.load_module(name, found_module[0], found_module[1], found_module[2])
            for mem_name, obj in inspect.getmembers(module):
                if inspect.isclass(obj) and inspect.getmodule(obj) is module:
                    obj_list.append(obj())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM