summaryrefslogtreecommitdiff
path: root/lib/spack/spack/util/classes.py
blob: 5e0b373ef8d2c3ad11bfbc629806c889cf4aefe2 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# Copyright 2013-2024 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
import inspect

import llnl.util.tty as tty
from llnl.util.lang import list_modules, memoized

from spack.util.naming import mod_to_class

__all__ = ["list_classes"]


@memoized
def list_classes(parent_module, mod_path):
    """Given a parent path (e.g., spack.platforms or spack.analyzers),
    use list_modules to derive the module names, and then mod_to_class
    to derive class names. Import the classes and return them in a list
    """
    classes = []

    for name in list_modules(mod_path):
        mod_name = "%s.%s" % (parent_module, name)
        class_name = mod_to_class(name)
        mod = __import__(mod_name, fromlist=[class_name])
        if not hasattr(mod, class_name):
            tty.die("No class %s defined in %s" % (class_name, mod_name))
        cls = getattr(mod, class_name)
        if not inspect.isclass(cls):
            tty.die("%s.%s is not a class" % (mod_name, class_name))

        classes.append(cls)

    return classes