### Install Modulegraph2 Source: https://modulegraph2.readthedocs.io/_sources/index.rst.txt Install or upgrade Modulegraph2 using pip. This command ensures you have the latest version. ```sh $ python3 -mpip \ install -U modulegraph2 ``` -------------------------------- ### Install modulegraph2 Source: https://modulegraph2.readthedocs.io/index.html Install or upgrade modulegraph2 using pip. This command ensures you have the latest version. ```bash $ python3 -mpip \ install -U modulegraph2 ``` -------------------------------- ### modulegraph2._utilities.FakePackage Source: https://modulegraph2.readthedocs.io/internals.html Represents a fake package, used as a workaround when a package cannot be imported directly, for example, due to syntax errors in its `__init__.py` file. ```APIDOC ## _class _modulegraph2._utilities.FakePackage ### Description Instances of these can be used to represent a fake package in `sys.modules`. Used as a workaround to fetch information about modules in packages when the package itself cannot be imported for some reason (for example due to having a SyntaxError in the module `__init__.py` file). ### Parameters * `_path` (list[str]_) - The path to the fake package directory. ``` -------------------------------- ### Basic ModuleGraph Usage Source: https://modulegraph2.readthedocs.io/_sources/examples.rst.txt Demonstrates initializing ModuleGraph, adding a module, finding nodes, and iterating through the graph. ```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) ``` -------------------------------- ### ModuleGraph.__init__() Source: https://modulegraph2.readthedocs.io/modulegraph2.html Create a new empty graph. ```APIDOC ## ModuleGraph.__init__() ### Description Create a new empty graph. ### Parameters * **use_stdlib_implies** (*)* – Use the built-in implied actions for the stdlib. * **use_builtin_hooks** (*)* – Use the built-in extension hooks ``` -------------------------------- ### Basic modulegraph2 Usage Source: https://modulegraph2.readthedocs.io/examples.html Demonstrates how to initialize ModuleGraph, add a module, find existing and non-existing nodes, and iterate through the graph. Use this for basic graph manipulation and inspection. ```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._depinfo.from_importinfo Source: https://modulegraph2.readthedocs.io/internals.html Creates a DependencyInfo instance from ImportInfo and additional details like whether it's part of a 'from ... import ...' statement and any renaming. ```APIDOC ## modulegraph2._depinfo.from_importinfo ### Description Create an `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. ``` -------------------------------- ### Report Graph Distributions Source: https://modulegraph2.readthedocs.io/modulegraph2.html Generate and print information about all distributions used within the graph. Optionally filter to include only distributions reachable from graph roots. ```python # Report all distributions mg.report() # Report only reachable distributions mg.report(reachable=True) ``` -------------------------------- ### ModuleGraph.add_dependencies_for_source() Source: https://modulegraph2.readthedocs.io/modulegraph2.html Add the modules imported by the Python code in source_code to the graph as roots. ```APIDOC ## ModuleGraph.add_dependencies_for_source() ### Description 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 Added in version 2.3. ``` -------------------------------- ### Utility Functions Source: https://modulegraph2.readthedocs.io/_sources/modulegraph2.rst.txt Utility functions for working with Python's sys.path and standard library module names. ```APIDOC ## Utilities ### Description Helper functions for module graph analysis. #### `modulegraph2.saved_sys_path()` Returns the saved sys.path. #### `modulegraph2.stdlib_module_names()` Returns a set of standard library module names. ``` -------------------------------- ### ModuleGraph Class Source: https://modulegraph2.readthedocs.io/_sources/modulegraph2.rst.txt The main class for creating and managing module dependency graphs. It provides methods for adding modules, scripts, distributions, and handling dependencies, exclusions, and callbacks. ```APIDOC ## Class modulegraph2.ModuleGraph ### Description Represents a graph of Python modules and their dependencies. ### Methods #### `__init__()` Initializes a new ModuleGraph instance. #### `add_module(module_name, module_path=None)` Adds a module to the graph. #### `add_script(script_path)` Adds a script file to the graph. #### `add_distribution(dist_name, dist_path)` Adds a Python distribution to the graph. #### `add_dependencies_for_source(source_path)` Adds dependencies for a given source file. #### `add_excludes(excludes)` Adds a list of modules to exclude from the graph. #### `add_implies(implies)` Adds a list of implied dependencies. #### `add_missing_hook(hook)` Adds a hook to be called when a missing module is encountered. #### `add_post_processing_hook(hook)` Adds a hook to be called after the graph has been processed. #### `hook_context()` Returns the current hook context. #### `import_module(module_name)` Imports a module and adds it to the graph. #### `import_package(package_name)` Imports a package and adds it to the graph. #### `distributions()` Returns a list of distributions in the graph. #### `report()` Generates a report of the module graph. ``` -------------------------------- ### create_importinfo Function Source: https://modulegraph2.readthedocs.io/internals.html A factory function to create an instance of the ImportInfo class, encapsulating the logic for initializing an ImportInfo object with provided details about an import statement. ```APIDOC ## Function _modulegraph2._importinfo.create_importinfo ### Description Create an `ImportInfo` instance. ### Parameters - **name** (tuple[str, str | None]) - Imported name. - **fromlist** (Iterable[tuple[str, str | None]] | None) - The “from” list of an import statement (or None). - **level** (int) - The import level, 0 for global imports and a positive number for relative imports. - **in_def** (bool) - Import statement inside a function definition. - **in_if** (bool) - Import statement inside either branch of an if-statement. - **in_tryexcept** (bool) - Import statement in the try or except blocks of a try statement. ### Returns A newly created `ImportInfo` instance. ``` -------------------------------- ### Distribution Classes and Functions Source: https://modulegraph2.readthedocs.io/_sources/modulegraph2.rst.txt Classes and functions for representing and querying Python distributions. ```APIDOC ## Distributions ### Description Classes and functions for handling Python distributions. #### `modulegraph2.PyPIDistribution` Represents a distribution found via PyPI. #### `modulegraph2.distribution_named(name)` Finds a distribution by its name. #### `modulegraph2.all_distributions()` Returns all distributions found. ``` -------------------------------- ### Extract AST Import Information Source: https://modulegraph2.readthedocs.io/internals.html Scans the Abstract Syntax Tree (AST) of a module to extract detailed information about import statements, including renames and their locations (global, function, try/except, conditional). It uses an explicit work queue to avoid recursion and stack exhaustion. ```python from typing import Iterator from ast import AST from modulegraph2._importinfo import ImportInfo 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. Parameters: node – The AST for a module Returns: An iterator that yields information about all located import statements """ pass ``` -------------------------------- ### modulegraph2.all_distributions Source: https://modulegraph2.readthedocs.io/modulegraph2.html Yields all distributions found on the search path. ```APIDOC ## modulegraph2.all_distributions(_path: Iterable[str] | None = None_) -> Iterator[PyPIDistribution] ### Description Yield all distributions found on the search path. ### Parameters - **path** (Iterable[str] | None, optional): Module search path (defaults to `sys.path`). ### Returns An iterator yielding `PyPIDistribution` objects. ``` -------------------------------- ### ModuleGraph.add_module() Source: https://modulegraph2.readthedocs.io/modulegraph2.html Add a module to the graph and process imports. Will not raise an exception for non-existing modules. ```APIDOC ## ModuleGraph.add_module() ### Description 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. ### Returns BaseNode ``` -------------------------------- ### Use Hook Context for Imports Source: https://modulegraph2.readthedocs.io/modulegraph2.html Utilize the `hook_context` as a context manager to safely call module import APIs within hook callbacks or other contexts where normal hook behavior is desired. ```python with mg.hook_context(): mg.import_module(some_node, "another_module") ``` -------------------------------- ### PyPIDistribution Class Source: https://modulegraph2.readthedocs.io/modulegraph2.html Represents information about a package distribution, including its identifier, name, version, files, import names, and extension attributes. ```APIDOC ## class _modulegraph2.PyPIDistribution(_identifier: str_, _name: str_, _version: str_, _files: set[str]_, _import_names: set[str]_, _extension_attributes: dict_) ### Description Information about a package distribution. ### Attributes - **identifier** (str): Unique identifier for the distribution for use with `modulegraph2.ObjectGraph`. - **name** (str): Name of the distribution (as it is found on PyPI). - **version** (str): Version of the distribution. - **files** (Set[str]): Files that are part of this distribution. - **import_names** (Set[str]): The importable names in this distribution (modules and packages). - **extension_attributes** (dict): A dictionary for use by users for the modulegraph2 library, not used by modulegraph2 itself. ### Methods #### contains_file(_filename: str | PathLike_) Check if a file is part of this distribution. Parameters: - **filename** (str | PathLike): The filename to look for. Returns: True if _filename_ is part of this distribution, otherwise False. ``` -------------------------------- ### modulegraph2._callback_list.CallbackList.add Source: https://modulegraph2.readthedocs.io/internals.html Adds a function to the callback list. ```APIDOC ## _modulegraph2._callback_list.CallbackList.add ### Description Add a _function_ to the callback list. ### Parameters * **function** – Function to be added ``` -------------------------------- ### Split Package Name Utility Source: https://modulegraph2.readthedocs.io/internals.html Utility function to split a fully qualified module name into its package and module name components. The package component is None for top-level modules. ```Python def split_package(_name : str_) -> tuple[str | None, str]: """ Return (package, name) given a fully qualified module name package is `None` for toplevel modules """ ``` -------------------------------- ### ModuleGraph.add_script() Source: https://modulegraph2.readthedocs.io/modulegraph2.html Add a script to the module graph and process imports. ```APIDOC ## ModuleGraph.add_script() ### Description 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 ``` -------------------------------- ### ModuleGraph.report Source: https://modulegraph2.readthedocs.io/modulegraph2.html Prints information about nodes reachable from the graph roots to a specified file stream. ```APIDOC ## ModuleGraph.report ### Description Print information about nodes reachable from the graph roots to the given file. ### Method None ### Endpoint None ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (None) None #### Response Example None ### Parameters * **file** (TextIO) - Optional - Description: Stream to write to. Defaults to stdout. ``` -------------------------------- ### FakePackage Class for ModuleGraph Source: https://modulegraph2.readthedocs.io/internals.html Represents a fake package for sys.modules, used as a workaround when a package cannot be imported directly. This is useful for fetching module information when the package's __init__.py file has syntax errors. ```Python class FakePackage(_path : list[str]): """ Instances of these can be used to represent a fake package in `sys.modules`. Used as a workaround to fetch information about modules in packages when the package itself cannot be imported for some reason (for example due to having a SyntaxError in the module `__init__.py` file). """ ``` -------------------------------- ### modulegraph2.stdlib_module_names Source: https://modulegraph2.readthedocs.io/modulegraph2.html Returns a list of all module names present in the Python standard library. ```APIDOC ## modulegraph2.stdlib_module_names() -> list[str] ### Description Return a list of modules in the standard library. ``` -------------------------------- ### modulegraph2._callback_list.FirstNotNone.__call__ Source: https://modulegraph2.readthedocs.io/internals.html Calls functions in the callback list in reverse order of addition and returns the first result that is not None. If no function returns a non-None value, None is returned. ```APIDOC ## _modulegraph2._callback_list.FirstNotNone.__call__ ### Description 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` ``` -------------------------------- ### ImportInfo Class Source: https://modulegraph2.readthedocs.io/internals.html Represents information about an import statement found in the Abstract Syntax Tree (AST) for a module or script. It stores details like the module name, import level, names being imported, and context within the code. ```APIDOC ## Class _modulegraph2._importinfo.ImportInfo ### Description Information about an import statement found in the AST for a module or script. ### Attributes - **import_module** (modulegraph2._importinfo.import_name) - The name of the module being imported. - **import_level** (int) - Number of dots at the start of an imported name, 0 for global imports, 1 or higher for relative imports. - **import_names** (set[modulegraph2._importinfo.import_name]) - The set of names imported with `from import_module import ...`. - **star_import** (bool) - True if this describes `from import_module import *`. - **is_in_function** (bool) - True if this describes an import statement in a function definition. - **is_in_conditional** (bool) - True if this describes an import statement in either branch of a conditional statement. - **is_in_tryexcept** (bool) - True if this describes an import statement in the `try` or `except` blocks of a try statement. ### Properties - **is_global** (bool) - True if this describes an import statement at module level. - **is_optional** (bool) - True if this describes an import statement that might be optional. ``` -------------------------------- ### Add Post-Processing Hook Source: https://modulegraph2.readthedocs.io/modulegraph2.html Attach a function to be executed after a node has been fully processed. Multiple hooks can be added and will run once per node, even if re-processed. ```python def post_process_node(graph, node): # Custom logic to run after a node is processed print(f"Node {node.name} fully processed.") mg.add_post_processing_hook(post_process_node) ``` -------------------------------- ### modulegraph2._callback_list.FirstNotNone.add Source: https://modulegraph2.readthedocs.io/internals.html Adds a function to the callback list. ```APIDOC ## _modulegraph2._callback_list.FirstNotNone.add ### Description Add _function_ to the callback list ### Parameters * **function** – Function to add to the list ``` -------------------------------- ### Import Module within Hooks Source: https://modulegraph2.readthedocs.io/modulegraph2.html Programmatically import a module and establish a dependency edge. This method is intended for use within hook callbacks and does not fully update the graph immediately. ```python importing_node = ... # A BaseNode instance imported_node = mg.import_module(importing_node, "module_to_import") ``` -------------------------------- ### ModuleGraph.add_distribution() Source: https://modulegraph2.readthedocs.io/modulegraph2.html Add a package distribution to the graph, with references to all importable names in that distribution. ```APIDOC ## ModuleGraph.add_distribution() ### Description 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._callback_list.CallbackList.__call__ Source: https://modulegraph2.readthedocs.io/internals.html Calls every callback in the list with the provided arguments in reverse order of insertion. The results of the called functions are ignored. ```APIDOC ## _modulegraph2._callback_list.CallbackList.__call__ ### Description 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 ``` -------------------------------- ### import_name Class Source: https://modulegraph2.readthedocs.io/internals.html Represents a value for an imported name, storing the name itself and any alias used with an 'as' clause. ```APIDOC ## Class _modulegraph2._importinfo.import_name ### Description Value representing an imported name. The string value itself is the imported name, the _asname_ attribute contains a rename from an “as” clause. ### Attributes - **asname** (str | None) - Renamed name from an “as” clause. ``` -------------------------------- ### MissingModule Class Source: https://modulegraph2.readthedocs.io/modulegraph2.html Represents a module that was imported but could not be located. It stores the name of the missing module. ```APIDOC ## class _modulegraph2.MissingModule(_module_name_) ### Description Node representing a name that is imported, but could not be located. ``` -------------------------------- ### modulegraph2._bytecode_tools.extract_bytecode_info Source: https://modulegraph2.readthedocs.io/internals.html Extracts key information from a module or script's code object, including all imports, written global names, and read global names. ```APIDOC ## modulegraph2._bytecode_tools.extract_bytecode_info ### Description 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 ``` -------------------------------- ### Import Package within Hooks Source: https://modulegraph2.readthedocs.io/modulegraph2.html Add all modules within a specified package to the graph and process their imports. This method is for hook usage, does not fully update the graph, and only supports filesystem-found packages. ```python importing_node = ... # A BaseNode instance mg.import_package(importing_node, "package_name") ``` -------------------------------- ### DependencyInfo Class Source: https://modulegraph2.readthedocs.io/modulegraph2.html Represents information about the dependency edge between two graph nodes. It is a frozen dataclass. ```APIDOC ## class _modulegraph2.DependencyInfo(_is_optional: bool_, _is_global: bool_, _in_fromlist: bool_, _imported_as: str | None_) ### Description A frozen dataclass representing information about the dependency edge between two graph nodes. ### Attributes - **is_optional** (bool): True if the import appears to be optional. - **is_global** (bool): True if the import affects global names in the module. - **in_fromlist** (bool): True if the name is imported in the name list of an `from ... import ...` statement. - **imported_as** (str | None): Rename for this module (`import ... as impoted_as`), None when there is no `as` clause. ``` -------------------------------- ### ModuleGraph.hook_context Source: https://modulegraph2.readthedocs.io/modulegraph2.html Provides a context manager to use hook APIs outside of a hook callback, allowing for programmatic imports within a controlled environment. ```APIDOC ## ModuleGraph.hook_context ### Description Context manager that allows using hook APIs outside of a hook callback. ### Method None ### Endpoint None ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python with mg.hook_context(): mg.import_module(...) ``` ### Response #### Success Response (None) None #### Response Example None ``` -------------------------------- ### modulegraph2._bytecode_tools._all_code_objects Source: https://modulegraph2.readthedocs.io/internals.html Yields all code objects directly and indirectly referenced from a given code object, managing a work queue to avoid stack exhaustion. It returns tuples of child code objects and their parent reference chains. ```APIDOC ## modulegraph2._bytecode_tools._all_code_objects ### Description 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. ### Parameters * **code** – A code object ### Returns An iterator that yields tuples _(child_code, parents)_ , where _parents_ is a list all code objects in the reference chain from _code_. ``` -------------------------------- ### modulegraph2.saved_sys_path Source: https://modulegraph2.readthedocs.io/modulegraph2.html A context manager that restores `sys.path` upon exiting the `with` block. ```APIDOC ## modulegraph2.saved_sys_path() ### Description Contextmanager that will restore the value of `sys.path` when leaving the `with` block. ``` -------------------------------- ### modulegraph2._utilities.split_package Source: https://modulegraph2.readthedocs.io/internals.html Utility function to split a fully qualified module name into its package and module name components. ```APIDOC ## modulegraph2._utilities.split_package ### Description Return (package, name) given a fully qualified module name. Package is `None` for toplevel modules. ### Method Signature `split_package(_name : str_) -> tuple[str | None, str]` ### Parameters * `_name` (str_) - The fully qualified module name. ### Returns * `tuple[str | None, str]` - A tuple containing the package name (or None if toplevel) and the module name. ``` -------------------------------- ### ModuleGraph.distributions Source: https://modulegraph2.readthedocs.io/modulegraph2.html Yields all distributions used within the graph. Optionally filters to include only distributions used by nodes reachable from the graph roots. ```APIDOC ## ModuleGraph.distributions ### 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 None ### Endpoint None ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (Iterator[PyPIDistribution]) None #### Response Example None ### Parameters * **reachable** (bool) - Optional - Description: If true only report on nodes that are reachable from a graph root, otherwise report on all nodes. ``` -------------------------------- ### modulegraph2._bytecode_tools._extract_single Source: https://modulegraph2.readthedocs.io/internals.html Extracts import information from a single bytecode object without recursing into child objects. It takes parameters to specify if the code object is for a function or class. ```APIDOC ## modulegraph2._bytecode_tools._extract_single ### Description Extract import information from a single bytecode object (without recursing into child objects). ### Parameters * **code** – The code object to process * **is_function_code** – True if this is a code object for a function or anything in a function. * **is_class_code** – True if this is the code object for a class ``` -------------------------------- ### modulegraph2._swig_support.swig_missing_hook Source: https://modulegraph2.readthedocs.io/internals.html Hook function to detect SWIG-related implicit relative imports in Python 2-style within packages. It adds the SWIG-loaded extension module as a global module to the graph, aligning with Python 3 import semantics. ```APIDOC ## modulegraph2._swig_support.swig_missing_hook ### Description Hook function to be used with `ModuleGraph.add_missing_hook`. This hook detects when a module in a package uses SWIG to load an extension module in the same package using Python 2-style implicit relative imports (that don’t work in Python 3). Adds this extension module as a global module to the graph, which corresponds to the Python 3 semantics of the import statement used in the code. ### Method Signature `swig_missing_hook(_graph : ModuleGraph_, _importing_module : BaseNode | None_, _missing_name : str_) -> BaseNode | None` ### Parameters * `_graph` (ModuleGraph_) - The module graph instance. * `_importing_module` (BaseNode | None_) - The module that is performing the import. * `_missing_name` (str_) - The name of the missing module. ### Returns * `BaseNode | None` - The added graph node for the SWIG extension module, or None if not applicable. ``` -------------------------------- ### ModuleGraph.import_package Source: https://modulegraph2.readthedocs.io/modulegraph2.html Adds all modules within a specified package to the graph and processes their imports. This method only supports packages found in the filesystem and is intended for hook usage. ```APIDOC ## ModuleGraph.import_package ### 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 None ### Endpoint None ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (BaseNode) None #### Response Example None ### Parameters * **importing_module** (BaseNode) - Description: The module that triggers this import. * **package_name** (str) - Description: Name of the package to import. ``` -------------------------------- ### AliasNode Class Source: https://modulegraph2.readthedocs.io/modulegraph2.html Represents a module alias, which is an imported name that refers to another module. It stores the alias name and the actual module it refers to. ```APIDOC ## class _modulegraph2.AliasNode(_module_name_, _actual_module_) ### Description 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. ``` -------------------------------- ### VirtualNode Class Source: https://modulegraph2.readthedocs.io/modulegraph2.html Represents a virtual module that is added to sys.modules by another module. It stores the name of the virtual module and the module that provides it. ```APIDOC ## class _modulegraph2.VirtualNode(_module_name_, _providing_module_) ### Description 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`. ``` -------------------------------- ### Add Missing Module Hook Source: https://modulegraph2.readthedocs.io/modulegraph2.html Register a callback function to attempt resolving missing modules. Hooks are executed in reverse order of addition, and the first non-None result is used. ```python def resolve_missing(graph, importing_module, module_name): # Custom logic to find or create a node for module_name if module_name == "special_module": return graph.add_module("special_module") return None mg.add_missing_hook(resolve_missing) ``` -------------------------------- ### ExcludedModule Class Source: https://modulegraph2.readthedocs.io/modulegraph2.html Represents a module that has been explicitly excluded by the user. It stores the name of the excluded module. ```APIDOC ## class _modulegraph2.ExcludedModule(_module_name_) ### Description Node representing a module that is explicitly excluded by the user. ``` -------------------------------- ### modulegraph2.distribution_named Source: https://modulegraph2.readthedocs.io/modulegraph2.html Finds a named distribution on the search path. ```APIDOC ## modulegraph2.distribution_named(_name: str_, _path: Iterable[str] | None = None_) -> PyPIDistribution | None ### Description Find a named distribution on the search path. ### Parameters - **name** (str): Distribution name to look for. - **path** (Iterable[str] | None, optional): Module search path (defaults to `sys.path`). ### Returns The distribution, or None. ``` -------------------------------- ### Graph Node Classes Source: https://modulegraph2.readthedocs.io/_sources/modulegraph2.rst.txt Defines the different types of nodes that can exist within the ModuleGraph, representing various Python entities like modules, packages, and scripts. ```APIDOC ## Graph Node Classes ### Description Classes representing nodes in the module graph. #### `modulegraph2.BaseNode` Base class for all nodes. #### `modulegraph2.Module` Represents a standard Python module. #### `modulegraph2.BuiltinModule` Represents a built-in Python module. #### `modulegraph2.BytecodeModule` Represents a module loaded from bytecode (.pyc). #### `modulegraph2.ExtensionModule` Represents a module implemented in C (e.g., .so, .pyd). #### `modulegraph2.FrozenModule` Represents a module included in a frozen application. #### `modulegraph2.SourceModule` Represents a module defined in a source file (.py). #### `modulegraph2.NamespacePackage` Represents a namespace package. #### `modulegraph2.Package` Represents a regular Python package. #### `modulegraph2.FrozenPackage` Represents a frozen package. #### `modulegraph2.Script` Represents a Python script file. #### `modulegraph2.VirtualNode` Represents a virtual node, not corresponding to a physical file. #### `modulegraph2.AliasNode` Represents an alias to another node. #### `modulegraph2.ExcludedModule` Represents a module that has been explicitly excluded. #### `modulegraph2.MissingModule` Represents a module that could not be found. #### `modulegraph2.InvalidRelativeImport` Represents an invalid relative import. ``` -------------------------------- ### Add Implied Dependencies Source: https://modulegraph2.readthedocs.io/modulegraph2.html Specify implied actions for modules that modulegraph2 cannot scan, such as extensions or modules using `__import__()`. This can also be used to mark an importable name as an alias or a virtual module. ```python mg.add_implies({ "my_package.submodule": ["os", "sys"], "my_alias": "real_module", "virtual_module": None # Placeholder for virtual module }) ``` -------------------------------- ### Special Aliases and Virtual Nodes Source: https://modulegraph2.readthedocs.io/_sources/modulegraph2.rst.txt Defines special node types for aliases and virtual representations. ```APIDOC ## Special Nodes ### Description Special node types. #### `modulegraph2.Alias` Represents an alias. #### `modulegraph2.Virtual` Represents a virtual node. ``` -------------------------------- ### ModuleGraph.import_module Source: https://modulegraph2.readthedocs.io/modulegraph2.html Imports a specified module and adds an edge from the importing module to the imported module. This method is intended for use by hooks and does not fully update the graph immediately. ```APIDOC ## ModuleGraph.import_module ### 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 None ### Endpoint None ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (BaseNode) Returns the graph node for _import_name_. #### Response Example None ### Parameters * **importing_module** (BaseNode) - Description: The module that triggers this import. * **import_name** (str) - Description: The name that should be imported. ``` -------------------------------- ### ModuleGraph.add_missing_hook Source: https://modulegraph2.readthedocs.io/modulegraph2.html Registers a hook function to resolve missing modules. Hooks are executed in reverse order of addition, and the first one to return a non-None value is used. ```APIDOC ## ModuleGraph.add_missing_hook ### Description 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. ### Method None ### Endpoint None ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (None) None #### Response Example None ### Parameters * **hook** (Callable[[ModuleGraph, BaseNode | None, str], BaseNode | None]) - Description: The hook function. Run `hook(self, importing_module, module_name)` before creating a `MissingModule` node for _module_name_. ``` -------------------------------- ### modulegraph2._callback_list.CallbackList.clear Source: https://modulegraph2.readthedocs.io/internals.html Clears all callbacks from the callback list. ```APIDOC ## _modulegraph2._callback_list.CallbackList.clear ### Description Clear the callback list ``` -------------------------------- ### modulegraph2._callback_list.FirstNotNone.clear Source: https://modulegraph2.readthedocs.io/internals.html Clears all callbacks from the callback list. ```APIDOC ## _modulegraph2._callback_list.FirstNotNone.clear ### Description Clear the callback list ``` -------------------------------- ### SWIG Missing Module Hook Source: https://modulegraph2.readthedocs.io/internals.html Hook function for ModuleGraph.add_missing_hook to handle SWIG-related implicit relative imports in Python 2 style. It ensures correct Python 3 semantics for such imports by adding the extension module as a global module. ```Python def swig_missing_hook(_graph : ModuleGraph_, _importing_module : BaseNode | None_, _missing_name : str_) -> BaseNode | None: """ Hook function to be used with `ModuleGraph.add_missing_hook`. This hook detects when a module in a package uses SWIG to load an extension module in the same package using Python 2-style implicit relative imports (that don’t work in Python 3). Adds this extension module as a global module to the graph, which corresponds to the Python 3 semantics of the import statement used in the code. """ ``` -------------------------------- ### Edge Attributes Source: https://modulegraph2.readthedocs.io/_sources/modulegraph2.rst.txt Defines the attributes associated with edges in the module graph, representing dependency information. ```APIDOC ## Edge Attributes ### Description Information about dependencies between nodes. #### `modulegraph2.DependencyInfo` Class representing the information about a dependency edge. ``` -------------------------------- ### ModuleGraph.add_post_processing_hook Source: https://modulegraph2.readthedocs.io/modulegraph2.html Adds a hook function that is executed after a node has been fully processed. Multiple hooks can be added. ```APIDOC ## ModuleGraph.add_post_processing_hook ### 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 None ### Endpoint None ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (None) None #### Response Example None ### Parameters * **hook** (Callable[[ModuleGraph, BaseNode], None]) - Description: The post processing hook. Run `hook(self, node)` when node is fully processed. The hook will be run most once per node, even if recipes or hooks re-processing of a node. ``` -------------------------------- ### modulegraph2._callback_list.as_T Source: https://modulegraph2.readthedocs.io/internals.html A MyPy helper function used to cast a function to type T, primarily for typing the __call__ attribute of CallbackList and FirstNotNone. ```APIDOC ## modulegraph2._callback_list.as_T ### Description MyPy helper: cast _function_ to type _T_. This is used to give the ___call___ attribute of `CallbackList` and `FirstNotNone` the right type. ### Parameters * **function** – Function to cast to type _T_ ``` -------------------------------- ### Exclude Modules from Graph Source: https://modulegraph2.readthedocs.io/modulegraph2.html Use this method to prevent specific module names from being fully processed by the graph. Excluded modules may appear as `ExcludedNode` but their dependencies won't be gathered. ```python mg.add_excludes(['my_module', 'another_module']) ``` -------------------------------- ### InvalidRelativeImport Class Source: https://modulegraph2.readthedocs.io/modulegraph2.html Represents a relative import that attempts to reference a location outside of a top-level package. It stores the name of the invalid relative import. ```APIDOC ## class _modulegraph2.InvalidRelativeImport(_module_name_) ### Description 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. ``` -------------------------------- ### ModuleGraph.add_implies Source: https://modulegraph2.readthedocs.io/modulegraph2.html Adds implied actions for the graph, which can represent dependencies, aliases, or virtual modules. This is useful for modules that modulegraph2 cannot scan directly. ```APIDOC ## ModuleGraph.add_implies ### Description Add implied actions for the graph. An implied action can be used for three purposes: A list of dependencies, an `Alias` for another node, or a `Virtual` module. ### Method None ### Endpoint None ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (None) None #### Response Example None ### Parameters * **implies** (dict[str, None | Alias | Virtual | Sequence[str]]) - Description: A mapping from module names to implied actions. ``` -------------------------------- ### modulegraph2._bytecode_tools._is_code_for_function Source: https://modulegraph2.readthedocs.io/internals.html Checks if a given code object is for a function or located within a function. It uses the code object, its parents, and a set of known function code objects for the check. ```APIDOC ## modulegraph2._bytecode_tools._is_code_for_function ### Description Check if this is the code object for a function or inside a function ### Parameters * **code** – The code object to check * **parents** – List of parents for this code object * **func_codes** – Set of code objects that are directly for functions ``` -------------------------------- ### ModuleGraph.add_excludes Source: https://modulegraph2.readthedocs.io/modulegraph2.html Excludes specified module names from being gathered in the graph. Excluded modules may appear as `ExcludedNode` but their dependencies will not be processed. ```APIDOC ## ModuleGraph.add_excludes ### Description 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. ### Method None ### Endpoint None ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (None) None #### Response Example None ### Parameters * **excluded_names** (Iterable[str]) - Description: An iterator yielding names to exclude. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.