Searches for a class within a package and its modules.
Parameters:
Name |
Type |
Description |
Default |
class_name
|
str
|
The name of the class to search for.
|
required
|
package_name
|
str
|
The name of the package to search within. Default is 'tinybig'.
|
'tinybig'
|
Returns:
Type |
Description |
str
|
The full module path of the class if found, otherwise an error message.
|
Source code in tinybig/util/utility.py
| def find_class_in_package(class_name: str, package_name: str = 'tinybig'):
"""
Searches for a class within a package and its modules.
Parameters
----------
class_name : str
The name of the class to search for.
package_name : str, optional
The name of the package to search within. Default is 'tinybig'.
Returns
-------
str
The full module path of the class if found, otherwise an error message.
"""
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}'"
|