### Install Modulegraph2 Source: https://github.com/ronaldoussoren/modulegraph2/blob/main/doc/index.md Install or upgrade Modulegraph2 using pip. ```sh $ python3 -mpip \ install -U modulegraph2 ``` -------------------------------- ### Basic ModuleGraph Initialization and Usage Source: https://github.com/ronaldoussoren/modulegraph2/blob/main/doc/examples.md Demonstrates how to create a ModuleGraph, add a built-in module, search for existing and non-existing modules, and iterate over the graph. Use this for initial setup and exploration. ```python import modulegraph2 mg = modulegraph2.ModuleGraph() mg.add_module("sys") mg.find_node("sys") # modulegraph2.BuiltinModule("sys") mg.find_node("os") # None for node in mg.iter_graph(): print(node) ``` -------------------------------- ### modulegraph2._distributions.distribution_for_file Source: https://github.com/ronaldoussoren/modulegraph2/blob/main/doc/internals.md Locates the distribution object that contains a given file. It searches through installed distributions based on the provided filename and an optional module search path. ```APIDOC ## modulegraph2._distributions.distribution_for_file(filename: str | PathLike, path: Iterable[str] | None) → [PyPIDistribution](modulegraph2.md#modulegraph2.PyPIDistribution) | None Find a distribution for a given file, for installed distributions. * **Parameters:** * **filename** – Filename to look for * **path** – Module search path (defaults to `sys.path`) * **Returns:** The distribution that contains *filename*, or None ``` -------------------------------- ### Extract All Code Objects from Code Source: https://github.com/ronaldoussoren/modulegraph2/blob/main/doc/internals.md Yields all code objects (including the starting one) referenced directly or indirectly from a given code object. It manages a work queue to prevent stack overflow. ```python def _all_code_objects(code: CodeType) -> Iterator[tuple[CodeType, list[CodeType]]]: """Yield all code objects directly and indirectly referenced from *code* (including *code* itself). This could explicitly manages a work queue and does not recurse to avoid exhausting the stack. :param code: A code object :return: An iterator that yields tuples *(child_code, parents)*, where *parents* is a list all code objects in the reference chain from *code*. """ pass ``` -------------------------------- ### modulegraph2.InvalidRelativeImport Source: https://github.com/ronaldoussoren/modulegraph2/blob/main/doc/modulegraph2.md Represents a relative import that attempts to reference a location outside of a top-level package. It stores the module name, which starts with one or more dots. ```APIDOC ## class modulegraph2.InvalidRelativeImport(module_name) Bases: [`BaseNode`](#modulegraph2.BaseNode) Node representing a relative import that refers to a location outside of a toplevel package. The name is a name starting with one or more dots. ``` -------------------------------- ### modulegraph2.Package Source: https://github.com/ronaldoussoren/modulegraph2/blob/main/doc/modulegraph2.md Represents a namespace package with an __init__ module. It inherits from BaseNode and includes attributes for the package name, loader, distribution, filename, extension attributes, the init_module, search path, data files presence, and namespace type. ```APIDOC ## class modulegraph2.Package ### Description Node representing a namespace package with an `__init__` module. ### Inheritance Bases: [`BaseNode`](#modulegraph2.BaseNode) ### Attributes - **name**: str - **loader**: Loader | None - **distribution**: [PyPIDistribution](#modulegraph2.PyPIDistribution) | None - **filename**: Path | None - **extension_attributes**: dict - **init_module**: [BaseNode](#modulegraph2.BaseNode) - **search_path**: list[Path] - **has_data_files**: bool - **namespace_type**: str | None ### Property `globals_read` The globals read from by the module __init__ ### Property `globals_written` The globals written to by the module __init__ ``` -------------------------------- ### Using ModuleGraph Hooks Source: https://github.com/ronaldoussoren/modulegraph2/blob/main/doc/modulegraph2.md Demonstrates how to use the hook_context manager to call hook APIs outside of a hook callback. This is useful for performing actions like importing modules within a controlled context. ```Python with mg.hook_context(): mg.import_module(...) ``` -------------------------------- ### modulegraph2._depinfo.from_importinfo Source: https://github.com/ronaldoussoren/modulegraph2/blob/main/doc/internals.md Creates a DependencyInfo instance from ImportInfo and other relevant details. This function is used internally to construct dependency information. ```APIDOC ## modulegraph2._depinfo.from_importinfo(import_info: [ImportInfo](#modulegraph2._importinfo.ImportInfo), in_fromlist: bool, name: str | None) Create an [`DependencyInfo`](modulegraph2.md#modulegraph2.DependencyInfo) instance from an `ImportInfo` and additional information. * **Parameters:** * **import_info** – The `ImportInfo` found by the AST or bytecode scanners * **in_fromlist** – True if the import refers to a name in the namelist from an `from ... imoprt ...` statement. * **name** – Rename for the module (`import ... as name`), None when there was no `as` clause. ``` -------------------------------- ### Importing a Package within a Hook Source: https://github.com/ronaldoussoren/modulegraph2/blob/main/doc/modulegraph2.md Illustrates how to import all modules within a package and process their imports. This method is designed for hooks and handles cases where the package name might refer to a module or a non-existent package. It only supports packages found in the filesystem. ```Python mg.import_package(importing_module, package_name) ``` -------------------------------- ### modulegraph2.NamespacePackage Source: https://github.com/ronaldoussoren/modulegraph2/blob/main/doc/modulegraph2.md Represents an implicit namespace package (PEP 420). It inherits from BaseNode and includes attributes for the package name, loader, distribution, filename, extension attributes, search path, and whether it has data files. ```APIDOC ## class modulegraph2.NamespacePackage ### Description Node representing an implicit namespace package (PEP 420). ### Inheritance Bases: [`BaseNode`](#modulegraph2.BaseNode) ### Attributes - **name**: str - **loader**: Loader | None - **distribution**: [PyPIDistribution](#modulegraph2.PyPIDistribution) | None - **filename**: Path | None - **extension_attributes**: dict - **search_path**: list[Path] - **has_data_files**: bool ### Property `globals_read` Always an empty set ### Property `globals_written` Always an empty set ``` -------------------------------- ### ModuleGraph._run_stack Source: https://github.com/ronaldoussoren/modulegraph2/blob/main/doc/internals.md Processes all items in the delayed work queue until the queue is empty. ```APIDOC ## ModuleGraph._run_stack() → None ### Description Process all items in the delayed work queue, until there is no more work. ``` -------------------------------- ### modulegraph2.all_distributions Source: https://github.com/ronaldoussoren/modulegraph2/blob/main/doc/modulegraph2.md Yields all package distributions found on the specified module search path. If no path is provided, it defaults to sys.path. ```APIDOC ### modulegraph2.all_distributions(path: Iterable[str] | None = None) → Iterator[[PyPIDistribution](#modulegraph2.PyPIDistribution)] Yield all distributions found on the search path. * **Parameters:** **path** – Module search path (defaults to `sys.path`). ``` -------------------------------- ### Extract AST Import Information Source: https://github.com/ronaldoussoren/modulegraph2/blob/main/doc/internals.md Scans the Abstract Syntax Tree (AST) of a module to find import statements. It provides detailed information including renames and the context of imports (global, function, try/except, conditional). This function uses a work queue to avoid stack exhaustion. ```python def extract_ast_info(node: AST) -> Iterator[ImportInfo]: """Scan the AST for a module to look for import statements. The AST scanner gives the most detailed information about import statements, and includes information about renames (import ... as ...), and the location of imports (global, in a function, in a try/except statement, in a conditional statement). The scanner explicitly manages a work queue and will not recurse to avoid exhausting the stack. :param node: The AST for a module :return: An iterator that yields information about all located import statements """ pass ``` -------------------------------- ### CallbackList Class Source: https://github.com/ronaldoussoren/modulegraph2/blob/main/doc/internals.md Manages a list of callback functions that are executed in reverse order of insertion. Useful for event handling or chaining operations. ```APIDOC ## class modulegraph2._callback_list.CallbackList A sequence of callbacks that are called in reverse order of insertion. ### __call__(*args, **kwds) Call every callback in the callback list with the given arguments. The callbacks are called in reverse order of inserting. The result of the called functions is ignored. * **Parameters:** * **args** – Positional arguments for the function * **kwds** – Keyword arguments for the function ### add(function: T) Add a *function* to the callback list. * **Parameters:** **function** – Function to be added ### clear() Clear the callback list ``` -------------------------------- ### modulegraph2._importinfo.create_importinfo Source: https://github.com/ronaldoussoren/modulegraph2/blob/main/doc/internals.md Creates an ImportInfo instance to represent an imported name, including details about its context within the import statement. ```APIDOC ## modulegraph2._importinfo.create_importinfo(name: tuple[str, str | None], fromlist: Iterable[tuple[str, str | None]] | None, level: int, in_def: bool, in_if: bool, in_tryexcept: bool) ### Description Create an [`ImportInfo`](#modulegraph2._importinfo.ImportInfo) instance. ### Parameters * **name** – imported name * **fromlist** – The “from” list of an import statement (or None) * **level** – The import level, 0 for global imports and a positive number for relative imoprts. * **in_def** – Import statement inside a function definition * **in_if** – Import statement inside either branch of an if-statement * **in_tryexcept** – Import statement in the try or except blocks of a try statement. ### Returns A newly created [`ImportInfo`](#modulegraph2._importinfo.ImportInfo) instance. ``` -------------------------------- ### FirstNotNone Class Source: https://github.com/ronaldoussoren/modulegraph2/blob/main/doc/internals.md A callback list that returns the first non-None result from its executed callbacks. Useful for scenarios where only one callback needs to provide a valid output. ```APIDOC ## class modulegraph2._callback_list.FirstNotNone A sequence of callbacks that are called in reverse order of insertion, and where the first result is used. ### __call__(*args, **kwds) Call the functions in the callback list in reverse order of addition. Return the first result that is not `None`. * **Parameters:** * **args** – Posititional arguments for the callback * **kwds** – Keyword arguments for the callback * **Returns:** The first not `None` result or `None` ### add(function: T) Add *function* to the callback list * **Parameters:** **function** – Function to add to the list ### clear() Clear the callback list ``` -------------------------------- ### ModuleGraph.report Source: https://github.com/ronaldoussoren/modulegraph2/blob/main/doc/modulegraph2.md Prints information about nodes reachable from the graph roots to a specified file stream. Defaults to standard output. ```APIDOC ## ModuleGraph.report(file: ~typing.TextIO = <_io.TextIOWrapper name='' mode='w' encoding='utf-8'>) -> None ### Description Print information about nodes reachable from the graph roots to the given file. ### Method GET ### Endpoint /ModuleGraph/report ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **file** (~typing.TextIO) - Optional - Stream to write to ### Request Example ```json { "file": "" } ``` ### Response #### Success Response (200) None #### Response Example ```json null ``` ``` -------------------------------- ### Printing ModuleGraph Report Source: https://github.com/ronaldoussoren/modulegraph2/blob/main/doc/modulegraph2.md Prints information about nodes reachable from the graph roots to a specified file. Defaults to writing to standard output. ```Python mg.report() ``` -------------------------------- ### Reporting Distributions in ModuleGraph Source: https://github.com/ronaldoussoren/modulegraph2/blob/main/doc/modulegraph2.md Yields all distributions used in the graph. By default, it reports only on distributions used by nodes reachable from graph roots. This method does not report PyPIDistributions that are nodes in the graph unless they are also the 'distribution' attribute of a node. ```Python mg.distributions(reachable=True) ``` -------------------------------- ### ModuleGraph._load_module Source: https://github.com/ronaldoussoren/modulegraph2/blob/main/doc/internals.md Adds a node for a specific module to the graph and processes its import statements. ```APIDOC ## ModuleGraph._load_module(importing_module: [BaseNode](modulegraph2.md#modulegraph2.BaseNode) | None, module_name: str) → [BaseNode](modulegraph2.md#modulegraph2.BaseNode) ### Description Add a node for a specific module. The module must not be part of the graph, and the module_name must be an absolute name (not a relative import. This not just adds the loaded module to the graph, but also pushed functions to the work stack that will process the import statements in *module_name*. ### Parameters * **importing_module** – The node triggering this import * **module_name** – The name to be loaded ### Returns A new node for *module_name* ``` -------------------------------- ### ModuleGraph._load_script Source: https://github.com/ronaldoussoren/modulegraph2/blob/main/doc/internals.md Adds a Script node to the graph and processes its import statements, handling potential file and syntax errors. ```APIDOC ## ModuleGraph._load_script(script_path: PathLike) → [Script](modulegraph2.md#modulegraph2.Script) ### Description Add a [`Script`](modulegraph2.md#modulegraph2.Script) node to the graph. The graph not contain a script with *script_path* as its filesystem location. This also pushes work to the stack to process import statements in the script. ### Parameters **script_path** – Filesystem path for a script ### Raises * **OSError** – If the script cannot be opened * **SyntaxError** – If the script is invalid ``` -------------------------------- ### modulegraph2._distributions.create_distribution Source: https://github.com/ronaldoussoren/modulegraph2/blob/main/doc/internals.md Constructs a PyPIDistribution object for a given distribution information directory. This is an internal utility for processing package metadata. ```APIDOC ## modulegraph2._distributions.create_distribution(distribution_file: str) → [PyPIDistribution](modulegraph2.md#modulegraph2.PyPIDistribution) Create a distribution object for a given dist-info directory. * **Parameters:** **distribution_file** – Filename for a dist-info directory Returns : A [`PyPIDistribution`](modulegraph2.md#modulegraph2.PyPIDistribution) for *distribution_file* ``` -------------------------------- ### Extract Bytecode Information from Module/Script Source: https://github.com/ronaldoussoren/modulegraph2/blob/main/doc/internals.md Extracts import statements, global variable writes, and global variable reads from the bytecode of a module or script. Returns a tuple containing these three pieces of information. ```python def extract_bytecode_info(code: CodeType) -> tuple[list[ImportInfo], set[str], set[str]]: """Extract interesting information from the code object for a module or script Returns a tuple of three items: 1) List of all imports 2) A set of global names written 3) A set of global names read by """ pass ``` -------------------------------- ### ModuleGraph._create_missing_module Source: https://github.com/ronaldoussoren/modulegraph2/blob/main/doc/internals.md Creates a MissingModule node for a given module name, attempting to resolve it using missing hooks if available. ```APIDOC ## ModuleGraph._create_missing_module(importing_module: [BaseNode](modulegraph2.md#modulegraph2.BaseNode) | None, module_name: str) → [BaseNode](modulegraph2.md#modulegraph2.BaseNode) ### Description Create a MissingModule node for ‘module_name’, after checking if one of the missing hooks can provide a node. ### Parameters * **imoprting_module** – The node that triggered the import. * **module_name** – The name that cannot be resolved. ### Returns A new node, either the result of one of the hooks or a new [`MissingModule`](modulegraph2.md#modulegraph2.MissingModule). ``` -------------------------------- ### Importing a Module within a Hook Source: https://github.com/ronaldoussoren/modulegraph2/blob/main/doc/modulegraph2.md Shows how to import a specific module and add an edge to the graph. This API is intended for use within hooks and does not fully update the graph immediately after calling. ```Python mg.import_module(importing_module, import_name) ``` -------------------------------- ### modulegraph2.FrozenPackage Source: https://github.com/ronaldoussoren/modulegraph2/blob/main/doc/modulegraph2.md Represents a Python package frozen into an executable, with source code available but not on the filesystem. It inherits from Package and includes all its attributes, plus a version added note. ```APIDOC ## class modulegraph2.FrozenPackage ### Description Node representing a python package that is frozen into an executable. This has source code available, but not on the filesystem. ### Inheritance Bases: [`Package`](#modulegraph2.Package) ### Attributes - **name**: str - **loader**: Loader | None - **distribution**: [PyPIDistribution](#modulegraph2.PyPIDistribution) | None - **filename**: Path | None - **extension_attributes**: dict - **init_module**: [BaseNode](#modulegraph2.BaseNode) - **search_path**: list[Path] - **has_data_files**: bool - **namespace_type**: str | None ### Versionadded Added in version 2.4. ``` -------------------------------- ### modulegraph2.BuiltinModule Source: https://github.com/ronaldoussoren/modulegraph2/blob/main/doc/modulegraph2.md Represents a built-in extension module. It inherits from the base Module class and contains information about the module's name, loader, distribution, filename, extension attributes, and global read/written sets. ```APIDOC ## class modulegraph2.BuiltinModule ### Description Node representing a built-in extension module. ### Inheritance Bases: [`Module`](#modulegraph2.Module) ### Attributes - **name**: str - **loader**: Loader | None - **distribution**: [PyPIDistribution](#modulegraph2.PyPIDistribution) | None - **filename**: Path | None - **extension_attributes**: dict - **globals_written**: set[str] - **globals_read**: set[str] - **code**: CodeType | None ``` -------------------------------- ### ModuleGraph.add_module Source: https://github.com/ronaldoussoren/modulegraph2/blob/main/doc/modulegraph2.md Adds a module to the graph and processes its imports. It does not raise an exception for non-existing modules. ```APIDOC ## ModuleGraph.add_module(module_name: str) -> BaseNode Add a module to the graph and process imports. Will not raise an exception for non-existing modules. * **Parameters:** **module_name** (str) – Name of the module to import. ``` -------------------------------- ### modulegraph2.stdlib_module_names Source: https://github.com/ronaldoussoren/modulegraph2/blob/main/doc/modulegraph2.md Returns a list of all module names that are part of the Python standard library. ```APIDOC ### modulegraph2.stdlib_module_names() → list[str] Return a list of modules in the standard library ``` -------------------------------- ### modulegraph2.ExtensionModule Source: https://github.com/ronaldoussoren/modulegraph2/blob/main/doc/modulegraph2.md Represents a native extension module. This class inherits from Module and stores information like the module's name, loader, distribution, filename, extension attributes, and global read/written sets. ```APIDOC ## class modulegraph2.ExtensionModule ### Description Node representing a native extension module. ### Inheritance Bases: [`Module`](#modulegraph2.Module) ### Attributes - **name**: str - **loader**: Loader | None - **distribution**: [PyPIDistribution](#modulegraph2.PyPIDistribution) | None - **filename**: Path | None - **extension_attributes**: dict - **globals_written**: set[str] - **globals_read**: set[str] - **code**: CodeType | None ``` -------------------------------- ### ModuleGraph Class Source: https://github.com/ronaldoussoren/modulegraph2/blob/main/doc/modulegraph2.md Represents the dependency graph between Python modules and scripts. It allows adding modules, scripts, and distributions, and processing their imports. ```APIDOC ## class modulegraph2.ModuleGraph Class representing the dependency graph between a collection of python modules and scripts. * **Parameters:** * **use_stdlib_implies** (bool) - Use the built-in implied actions for the stdlib. * **use_builtin_hooks** (bool) - Use the built-in extension hooks ``` -------------------------------- ### ModuleGraph.distributions Source: https://github.com/ronaldoussoren/modulegraph2/blob/main/doc/modulegraph2.md Yields all distributions used within the graph. Optionally filters to include only distributions used by nodes reachable from the graph roots. ```APIDOC ## ModuleGraph.distributions(reachable: bool = True) -> Iterator[PyPIDistribution] ### Description Yield all distributions used in the graph. If reachable is True (default) this reports only on distributions used by nodes reachable from one of the graph roots, otherwise this reports on distributions used by any root. This will not report PyPIDistributions that are nodes in the graph, unless they are also the *distribution* attribute of a node. ### Method GET ### Endpoint /ModuleGraph/distributions ### Parameters #### Path Parameters None #### Query Parameters - **reachable** (bool) - Optional - IF true only report on nodes that are reachable from a graph root, otherwise report on all nodes. ### Request Example ```json null ``` ### Response #### Success Response (200) - **Iterator[PyPIDistribution]** - An iterator yielding PyPIDistribution objects. #### Response Example ```json [ { "name": "example_dist", "version": "1.0.0" } ] ``` ``` -------------------------------- ### modulegraph2.BytecodeModule Source: https://github.com/ronaldoussoren/modulegraph2/blob/main/doc/modulegraph2.md Represents a Python module for which only bytecode is available. It inherits from the base Module class and includes details such as name, loader, distribution, filename, extension attributes, and global read/written sets. ```APIDOC ## class modulegraph2.BytecodeModule ### Description Node representing a python module for which only bytecode is available. ### Inheritance Bases: [`Module`](#modulegraph2.Module) ### Attributes - **name**: str - **loader**: Loader | None - **distribution**: [PyPIDistribution](#modulegraph2.PyPIDistribution) | None - **filename**: Path | None - **extension_attributes**: dict - **globals_written**: set[str] - **globals_read**: set[str] - **code**: CodeType | None ``` -------------------------------- ### Extract Single Bytecode Object Information Source: https://github.com/ronaldoussoren/modulegraph2/blob/main/doc/internals.md Extracts import information from a single bytecode object without recursing into child objects. This is useful for analyzing specific code segments. ```python def _extract_single(code: CodeType, is_function_code: bool, is_class_code: bool): """Extract import information from a single bytecode object (without recursing into child objects). :param code: The code object to process :param is_function_code: True if this is a code object for a function or anything in a function. :param is_class_code: True if this is the code object for a class """ pass ``` -------------------------------- ### ModuleGraph.add_dependencies_for_source Source: https://github.com/ronaldoussoren/modulegraph2/blob/main/doc/modulegraph2.md Adds modules imported by the provided Python source code to the graph as roots. This is useful for analyzing code snippets or dynamically generated code. ```APIDOC ## ModuleGraph.add_dependencies_for_source(source_code: str) -> None Add the modules imported by the Python code in *source_code* to the graph as roots. * **Parameters:** **source_code** (str) – Source code for a python script or module Versionadded Added in version 2.3. ``` -------------------------------- ### ModuleGraph.import_package Source: https://github.com/ronaldoussoren/modulegraph2/blob/main/doc/modulegraph2.md Adds all modules within a specified package to the graph and processes their imports. This method is designed for hook usage and handles non-existent packages or modules gracefully. It only supports packages found in the filesystem. ```APIDOC ## ModuleGraph.import_package(importing_module: BaseNode, package_name: str) -> BaseNode ### Description Add all modules in a package to the graph and process imports. Will not raise an exception for non-existing packages or when the *package_name* refers to a module instead of a package. This is an API to be used by hooks. The graph is not fully updated after calling this method. This method only supports packages that are found in the filesystem. ### Method POST ### Endpoint /ModuleGraph/import_package ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **importing_module** (BaseNode) - Required - The module that triggers this import - **package_name** (str) - Required - Name of the package to import ### Request Example ```json { "importing_module": "module_node_reference", "package_name": "example_package" } ``` ### Response #### Success Response (200) - **BaseNode** - The graph node for the main package module. #### Response Example ```json { "name": "example_package", "loader": null, "distribution": null, "filename": null, "extension_attributes": {} } ``` ``` -------------------------------- ### ModuleGraph.import_module Source: https://github.com/ronaldoussoren/modulegraph2/blob/main/doc/modulegraph2.md Imports a module by its name and adds an edge from the importing module to the imported module in the graph. This API is intended for use within hooks and does not fully update the graph immediately. ```APIDOC ## ModuleGraph.import_module(importing_module: BaseNode, import_name: str) -> BaseNode ### Description Import ‘import_name’ and add an edge from ‘module’ to ‘import_name’. This is an API to be used by hooks. The graph is not fully updated after calling this method. ### Method POST ### Endpoint /ModuleGraph/import_module ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **importing_module** (BaseNode) - Required - The module that triggers this import - **import_name** (str) - Required - The name that should be imported ### Request Example ```json { "importing_module": "module_node_reference", "import_name": "example_module" } ``` ### Response #### Success Response (200) - **BaseNode** - The graph node for *import_name*. #### Response Example ```json { "name": "example_module", "loader": null, "distribution": null, "filename": null, "extension_attributes": {} } ``` ``` -------------------------------- ### modulegraph2.DependencyInfo Source: https://github.com/ronaldoussoren/modulegraph2/blob/main/doc/modulegraph2.md A frozen dataclass representing information about the dependency edge between two graph nodes, including whether the import is optional, global, part of a 'from list', and if it was imported with an alias. ```APIDOC ## class modulegraph2.DependencyInfo(is_optional: bool, is_global: bool, in_fromlist: bool, imported_as: str | None) A frozen dataclass representing information about the dependency edge between two graph nodes. #### is_optional True if the import appears to be optional * **Type:** bool #### is_global True if the import affects global names in the module * **Type:** bool #### in_fromlist True if the name is imported in the name list of an `from ... import ...` statement * **Type:** bool #### imported_as Rename for this module (`import ... as impoted_as`), None when there is no `as` clause. * **Type:** str | None ``` -------------------------------- ### modulegraph2.Script Source: https://github.com/ronaldoussoren/modulegraph2/blob/main/doc/modulegraph2.md Represents a Python script. The node's name is the string representation of its full filename. It inherits from BaseNode and includes attributes for filename, code, and global read/written sets. ```APIDOC ## class modulegraph2.Script ### Description Node representing a Python script. The name of the node is the string representation of the full filename of the script. ### Inheritance Bases: [`BaseNode`](#modulegraph2.BaseNode) ### Attributes - **filename**: PathLike - **code**: CodeType | None ### Property `globals_written` Global varialbles written to * **Type:** set[str] ### Property `globals_read` Global variables read from * **Type:** set[str] ### Versionadded Added in version 2.2: The *code* attribute ``` -------------------------------- ### ModuleGraph.add_script Source: https://github.com/ronaldoussoren/modulegraph2/blob/main/doc/modulegraph2.md Adds a script to the module graph and processes its imports. This method can raise exceptions if the script is already in the graph, cannot be opened, or is syntactically invalid. ```APIDOC ## ModuleGraph.add_script(script_path: PathLike) -> Script Add a script to the module graph and process imports * **Parameters:** **script_path** (PathLike) – Filesystem path for the script to be added * **Returns:** The script node for the just added script * **Raises:** * **ValueError** – If the script is already part of the graph * **OSError** – If the script cannot be opened. * **SyntaxError** – If the script is invalid ``` -------------------------------- ### modulegraph2.PyPIDistribution Source: https://github.com/ronaldoussoren/modulegraph2/blob/main/doc/modulegraph2.md Stores information about a package distribution, including its identifier, name, version, files, and importable names. It also provides a method to check if a file belongs to the distribution. ```APIDOC ## class modulegraph2.PyPIDistribution(identifier: str, name: str, version: str, files: set[str], import_names: set[str], extension_attributes: dict) Information about a package distribution #### identifier Unique identifier fot the distribution for use with `modulegraph2.ObjectGraph` * **Type:** str #### name Name of the distribution (as it is found on PyPI) * **Type:** str #### files Files that are part of this distribution * **Type:** Set[str] #### import_names The importable names in this distribution (modules and packages) * **Type:** Set[str] #### extension_attributes A dictionary for use by users for the modulegraph2 library, not used by modulegraph2 itself. * **Type:** dict #### NOTE The information about distributions is fairly minimal at this point, and will be enhanced as needed. #### contains_file(filename: str | PathLike) Check if a file is part of this distribution. * **Parameters:** **filename** – The filename to look for * **Returns:** True if *filename* is part of this distribution, otherwise False. ``` -------------------------------- ### modulegraph2.FrozenModule Source: https://github.com/ronaldoussoren/modulegraph2/blob/main/doc/modulegraph2.md Represents a Python module that is frozen into an executable, with source code available but not on the filesystem. It inherits from Module and includes attributes for name, loader, distribution, filename, extension attributes, and global read/written sets. ```APIDOC ## class modulegraph2.FrozenModule ### Description Node representing a python module that is frozen into an executable. This has source code available, but not on the filesystem. ### Inheritance Bases: [`Module`](#modulegraph2.Module) ### Attributes - **name**: str - **loader**: Loader | None - **distribution**: [PyPIDistribution](#modulegraph2.PyPIDistribution) | None - **filename**: Path | None - **extension_attributes**: dict - **globals_written**: set[str] - **globals_read**: set[str] - **code**: CodeType | None ``` -------------------------------- ### modulegraph2.MissingModule Source: https://github.com/ronaldoussoren/modulegraph2/blob/main/doc/modulegraph2.md Represents a module that was imported but could not be located. It stores the module name. ```APIDOC ## class modulegraph2.MissingModule(module_name) Bases: [`BaseNode`](#modulegraph2.BaseNode) Node representing a name that is imported, but could not be located. ``` -------------------------------- ### ModuleGraph.hook_context Source: https://github.com/ronaldoussoren/modulegraph2/blob/main/doc/modulegraph2.md A context manager that enables the use of hook APIs outside of a hook callback. This is useful for performing import operations within a controlled environment. ```APIDOC ## ModuleGraph.hook_context() ### Description Context manager that allows using hook APIs outside of a hook callback. Usage: `with mg.hook_context(): mg.import_module(...)` ### Method GET ### Endpoint /ModuleGraph/hook_context ### Parameters None ### Request Example ```json null ``` ### Response #### Success Response (200) Iterator[None] #### Response Example ```json null ``` ``` -------------------------------- ### modulegraph2.SourceModule Source: https://github.com/ronaldoussoren/modulegraph2/blob/main/doc/modulegraph2.md Represents a Python module for which the source code is available. This class inherits from Module and stores attributes like name, loader, distribution, filename, extension attributes, and global read/written sets. ```APIDOC ## class modulegraph2.SourceModule ### Description Node representing a python module for which the source code is available. ### Inheritance Bases: [`Module`](#modulegraph2.Module) ### Attributes - **name**: str - **loader**: Loader | None - **distribution**: [PyPIDistribution](#modulegraph2.PyPIDistribution) | None - **filename**: Path | None - **extension_attributes**: dict - **globals_written**: set[str] - **globals_read**: set[str] - **code**: CodeType | None ``` -------------------------------- ### modulegraph2.distribution_named Source: https://github.com/ronaldoussoren/modulegraph2/blob/main/doc/modulegraph2.md Finds a named package distribution on the Python module search path. It takes the distribution name and an optional path, returning the distribution object or None if not found. ```APIDOC ### modulegraph2.distribution_named(name: str, path: Iterable[str] | None = None) → [PyPIDistribution](#modulegraph2.PyPIDistribution) | None Find a named distribution on the search path. * **Parameters:** * **name** – Distribution name to look for. * **path** – Module search path (defaults to `sys.path`) * **Returns:** The distribution, or None ``` -------------------------------- ### ModuleGraph.add_distribution Source: https://github.com/ronaldoussoren/modulegraph2/blob/main/doc/modulegraph2.md Adds a package distribution to the graph, including references to all importable names within that distribution. ```APIDOC ## ModuleGraph.add_distribution(distribution: PyPIDistribution | str) -> PyPIDistribution | str Add a package distribution to the graph, with references to all importable names in that distribution * **Parameters:** **distribution** (PyPIDistribution | str) – A distribution or distribution name Returns : The node added to the graph ``` -------------------------------- ### modulegraph2.saved_sys_path Source: https://github.com/ronaldoussoren/modulegraph2/blob/main/doc/modulegraph2.md A context manager that restores the value of sys.path upon exiting the 'with' block, ensuring the module search path is returned to its original state. ```APIDOC ### modulegraph2.saved_sys_path() Contextmanager that will restore the value of `sys.path` when leaving the `with` block. ``` -------------------------------- ### modulegraph2.AliasNode Source: https://github.com/ronaldoussoren/modulegraph2/blob/main/doc/modulegraph2.md Represents a module alias, which is an imported name that refers to another module. It stores the module name and the actual module it aliases. ```APIDOC ## class modulegraph2.AliasNode(module_name, actual_module) Bases: [`BaseNode`](#modulegraph2.BaseNode) Node representing a module alias, that is an imported name that refers to some other module. Attributes : actual_module : The module that this name aliases to. ``` -------------------------------- ### modulegraph2.VirtualNode Source: https://github.com/ronaldoussoren/modulegraph2/blob/main/doc/modulegraph2.md Represents a virtual module that is added to sys.modules by another module. It stores information about the module name and the providing module. ```APIDOC ## class modulegraph2.VirtualNode(module_name, providing_module) Bases: [`BaseNode`](#modulegraph2.BaseNode) Node representing a virtual module, that is added to `sys.modules` by some other module. Attributes : providing_module : The module that creates this module in `sys.modules`. ``` -------------------------------- ### ModuleGraph._implied_references Source: https://github.com/ronaldoussoren/modulegraph2/blob/main/doc/internals.md Checks for implied actions related to a module name, potentially returning a node if actions are implied. ```APIDOC ## ModuleGraph._implied_references(importing_module: [BaseNode](modulegraph2.md#modulegraph2.BaseNode) | None, module_name: str) → [BaseNode](modulegraph2.md#modulegraph2.BaseNode) | None ### Description Check implied actions for *module_name*. ### Parameters * **importing_module** – Module triggering the import * **module_name** – The name that should be imported ### Returns A node if their are implied actions, or `None` otherwise. ``` -------------------------------- ### ModuleGraph.add_post_processing_hook Source: https://github.com/ronaldoussoren/modulegraph2/blob/main/doc/modulegraph2.md Adds a hook function that will be executed after a node has been fully processed. Multiple hooks can be added by calling this method multiple times. ```APIDOC ## ModuleGraph.add_post_processing_hook(hook: Callable[[ModuleGraph, BaseNode], None]) -> None ### Description Add a hook function to be ran whenever a node is fully processed. It is possible to add multiple hooks by calling this method multiple times. ### Method POST ### Endpoint /ModuleGraph/add_post_processing_hook ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **hook** (Callable[[ModuleGraph, BaseNode], None]) - Required - The post processing hook. Run `hook(self, node)` ### Request Example ```json { "hook": "function_reference" } ``` ### Response #### Success Response (200) None #### Response Example ```json null ``` ``` -------------------------------- ### modulegraph2.ExcludedModule Source: https://github.com/ronaldoussoren/modulegraph2/blob/main/doc/modulegraph2.md Represents a module that has been explicitly excluded by the user. It stores the module name. ```APIDOC ## class modulegraph2.ExcludedModule(module_name) Bases: [`BaseNode`](#modulegraph2.BaseNode) Node representing a module that is explicitly excluded by the user. ``` -------------------------------- ### ModuleGraph.add_implies Source: https://github.com/ronaldoussoren/modulegraph2/blob/main/doc/modulegraph2.md Adds implied actions for the graph, which can be used to specify dependencies for modules that modulegraph2 cannot scan, mark importable names as aliases, or define virtual modules. ```APIDOC ## ModuleGraph.add_implies(implies: dict[str, None | Alias | Virtual | Sequence[str]]) -> None Add implied actions for the graph. An implied action can be used for three purposes: * A list of dependencies. > Commonly used to add module dependencies for modules > that modulegraph2 cannot scan, such as extensions and modules > using `__import__()`. * An `Alias` for another node Used to mark an importable name as an alias for some other module. An example of this is `os.path`, which is an alias to a platform specific path module (such as `posixpath`. * A `Virtual` module Used to mark an importable name as a virtual module that is added to `sys.modules` by some other module. * **Parameters:** **implies** (dict[str, None | Alias | Virtual | Sequence[str]]) – A mapping from module names to implied actions ``` -------------------------------- ### ModuleGraph.add_missing_hook Source: https://github.com/ronaldoussoren/modulegraph2/blob/main/doc/modulegraph2.md Adds a hook function that is called to attempt to resolve a missing module. The first hook to return a non-None value determines the resolution. ```APIDOC ## ModuleGraph.add_missing_hook(hook: Callable[[ModuleGraph, BaseNode | None, str], BaseNode | None]) -> None Add a hook function that’s used to try to resolve a missing module. The hook functions are called in reverse order of addition, and the result of the first hook that doesn’t return `None` is used in the graph. * **Parameters:** **hook** (Callable[[ModuleGraph, BaseNode | None, str], BaseNode | None]) – The hook function. Run `hook(self, importing_module, module_name)` before creating a [`MissingModule`](#modulegraph2.MissingModule) node for *module_name*. ``` -------------------------------- ### Check if Code Object is for a Function Source: https://github.com/ronaldoussoren/modulegraph2/blob/main/doc/internals.md Determines if a given code object is associated with a function or is nested within a function. It uses a set of known function code objects for comparison. ```python def _is_code_for_function(code: CodeType, parents: list[CodeType], func_codes: set[CodeType]) -> bool: """Check if this is the code object for a function or inside a function :param code: The code object to check :param parents: List of parents for this code object :param func_codes: Set of code objects that are directly for functions """ pass ``` -------------------------------- ### ModuleGraph.add_excludes Source: https://github.com/ronaldoussoren/modulegraph2/blob/main/doc/modulegraph2.md Excludes specified module names from being gathered into the graph. Excluded names may appear as ExcludedNode nodes. ```APIDOC ## ModuleGraph.add_excludes(excluded_names: Iterable[str]) -> None Exclude the names in “excludeded_names” from the graph Excluded names can end up as `ExcludedNode` nodes in the graph, but the dependencies of the actual module are not gathered. * excluded_names: An interator yielding names to exclude. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.