Skip to content

find_class_in_package

Source code in tinybig/util/utility.py
def find_class_in_package(class_name: str, package_name: str = 'tinybig'):
    try:
        # Import the package
        package = importlib.import_module(package_name)
    except ModuleNotFoundError:
        return f"Package '{package_name}' not found"

    # List all modules in the package
    for _, module_name, is_pkg in pkgutil.walk_packages(package.__path__, package.__name__ + '.'):
        if not is_pkg:  # We are only interested in modules, not sub-packages
            try:
                # Dynamically import the module
                module = importlib.import_module(module_name)

                # Check if the class exists in the module
                if hasattr(module, class_name):
                    # Ensure that it is indeed a class and not a different attribute
                    class_obj = getattr(module, class_name)
                    if inspect.isclass(class_obj):
                        # Return the full class path
                        return f"{module_name}.{class_name}"
            except ImportError:
                continue

    return f"Class '{class_name}' not found in package '{package_name}'"