Python 使用 curses 提示类型

Python Type hinting with curses

我想知道在这个函数的顶部我的类型注释中应该放些什么。

我有以下简单的例子:

import curses

def main(stdscr):
    stdscr.clear()

    stdscr.addstr(2, 0, "What is the type of stdscr?")
    stdscr.addstr(5, 0, "It is: {}".format(type(stdscr)))

    stdscr.refresh()
    stdscr.getkey()

curses.wrapper(main)

这个returns<type '_curses.curses window'>。这似乎不适用于类型提示,因为它有一个 space 。 预期结果将 WindowObject 列在 the documentation 中。我在 curses 模块本身找不到 WindowObject 的路径。 编辑:此处的文档不正确。

如何使用准确的类型注释编写 main?

你的问题是你看到的类型不是对象的真实类型,方法 type() 总是正确地告诉你类型,所以确保文档。是错的。

不幸的是,curses 模块似乎没有在 typeshed 中完全键入。有一些 preliminary work done a few months ago, but the Windows object has not been added yet. You can check the Python 3 'curses' stubs for yourself here and here.

目前,存根默认输入 curses.wrapper 为:

def wrapper(func, *args, **kwds): ...

...反过来,相当于:

def wrapper(func: Callable[..., Any], *args: Any, **kwds: Any): ...

所以,这意味着除了 Any.

之外,目前确实没有合适的类型可以分配给 main 函数的参数

就是说,如果您愿意,您可以贡献一些存根来自己完成 curses 模块! Window object 似乎并没有那么复杂,希望输入起来相对简单。

主要的困难可能是确定 'Window' 对象应该从哪里导入,如果它不存在于 curses 模块本身。您可能希望将 'Windows' 对象粘贴在 typing 模块本身中,就像 typing.re.Pattern and typing.re.Match.