Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
360 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...