Skip to content

get_module_data

Get the module data of the given code.

To get the module data of the given code, the code is parsed into an AST and then walked by an ASTWalker. The ModuleDataBuilder detects the scope of each node and builds a scope tree. The ModuleDataBuilder also collects all classes, functions, global variables, value nodes, target nodes, parameters, function calls, and function references.

Parameters:

Name Type Description Default
code str

The source code of the module whose module data is to be found.

required
module_name str

The name of the module, by default "".

''
path str | None

The path of the module, by default None.

None

Returns:

Type Description
ModuleData

The module data of the given module.

Raises:

Type Description
ValueError

If the code has invalid syntax.

Source code in src/library_analyzer/processing/api/purity_analysis/_get_module_data.py
def get_module_data(code: str, module_name: str = "", path: str | None = None) -> ModuleData:
    """Get the module data of the given code.

    To get the module data of the given code, the code is parsed into an AST and then walked by an ASTWalker.
    The ModuleDataBuilder detects the scope of each node and builds a scope tree.
    The ModuleDataBuilder also collects all classes, functions, global variables, value nodes, target nodes, parameters,
    function calls, and function references.

    Parameters
    ----------
    code :
        The source code of the module whose module data is to be found.
    module_name :
        The name of the module, by default "".
    path :
        The path of the module, by default None.

    Returns
    -------
    ModuleData
        The module data of the given module.

    Raises
    ------
    ValueError
        If the code has invalid syntax.
    """
    module_data_handler = ModuleDataBuilder()
    walker = ASTWalker(module_data_handler)
    try:
        module = astroid.parse(code, module_name, path)
    except astroid.AstroidSyntaxError as e:
        raise ValueError(f"Invalid syntax in code: {e}") from e
    walker.walk(module)

    scope = module_data_handler.children[0]  # Get the children of the root node, which are the scopes of the module

    return ModuleData(
        scope=scope,
        classes=module_data_handler.classes,
        functions=module_data_handler.functions,
        imports=module_data_handler.imports,
    )