What is the type hint for a (any) python module?

Question:

I would like to add the (Python3) type hint for a module (class ‘module’). The typing package doesn’t provide one, and types.ModuleType() is a constructor that returns a module object for a specific name.

Example:

import types
def foo(module: types.ModuleType):
   pass

at least in PyCharm results in

"Cannot find reference ModuleType in types.pyi".

Note that Python typing for module type doesn’t answer my question, as it does not explain that ModuleType is both a constructor as well as a type, as answered below.

Asked By: TheDiveO

||

Answers:

and types.ModuleType() is a constructor.

That doesn’t matter. types.ModuleType is still a reference to a type, just like str and int are. There is no need for a generic Module[typehint] annotation, so types.ModuleType is exacly what you need to use here.

For example, the official Python typeshed project provides a type hint annotation for sys.modules as:

from types import FrameType, ModuleType, TracebackType

# ...

modules: Dict[str, ModuleType]

Don’t be confused by the name here; types.ModuleType is a reference to the module type. It is not a separate factory function or something. The CamelCase name follows the convention of that module, and you use that reference because the type object is not otherwise available as a built-in. The types module assigns the value of type(sys) to the name.

If PyCharm is having issues with finding the types.ModuleType stubs, then that’s either a problem with PyCharm itself (a bug), or the stubs currently bundled are outdated, or you used an incomplete typeshed set of stubs. See the PyCharm documentation on how to use custom stubs to provide a fresh set.

If that doesn’t work, it may be a bug in PyCharm dealing with the concept of exporting type hints. Typeshed currently defines the ModuleType type hints in a separate module, which are then imported into the types.pyi stubfile using the from module import name as name syntax. PEP 484 states that imported type hints are not part of the stub unless you use the as syntax:

Modules and variables imported into the stub are not considered exported from the stub unless the import uses the import ... as ... form or the equivalent from ... import ... as ... form.

It may be that PyCharm doesn’t yet correctly handle such cases.

Answered By: Martijn Pieters