Search code examples
python-3.xmypypython-importlib

What is the type (for mypy) of a module created with importlib?


I'm loading a module with importlib as such:

from importlib.machinery import SourceFileLoader
from importlib.util import spec_from_loader, module_from_spec
from pathlib import Path
from typing import Union

PathStr = Union[Path, str]

def load_module(module_path:PathStr, module_name="module"):
    """Load and return a module"""
    loader = SourceFileLoader(module_name, module_path)
    spec = spec_from_loader(loader.name, loader)
    module = module_from_spec(spec)
    loader.exec_module(module)
    return module

What is the type of the module returned by the function? I cannot figure it out.


Solution

  • This similar answer say it all: https://stackoverflow.com/a/48981829/1603480

    Here is a summary for persistent information:The type annotation for importlib.import_module simply returns types.ModuleType

    From the typeshed source:

    def import_module(name: str, package: Optional[str] = ...) -> types.ModuleType: ...
    

    ... And then the author of the solution provides some suggestions to help mypy