python 3curses 包装器的类型提示

the*_*can 3 python curses type-hinting visual-studio-code

对于Python 3中的curses编程,使用curses.wrapper函数来封装curses程序、处理错误和设置是很有用的。

import curses

def main(stdscr):
    # Curses program here
    pass

curses.wrapper(main)
Run Code Online (Sandbox Code Playgroud)

但是如何向对象添加类型提示stdscr呢?添加类型提示将允许 IDE 为对象提供更好的智能感知stdscr并显示可用的方法和属性。(顺便说一句,我正在使用 Visual Studio Code)

下面的代码:

import curses

def main(stdscr):
    s = str(type(stdscr))
    stdscr.clear()
    stdscr.addstr(0,0,s)
    stdscr.refresh()
    stdscr.getkey()

curses.wrapper(main)
Run Code Online (Sandbox Code Playgroud)

...表明那type(stdscr)<class '_curses.window'>

但这不起作用:

import curses
import _curses

# This does not work:
def main(stdscr: _curses.window):
    # No intellisense provided for stdscr
    pass

curses.wrapper(main)
Run Code Online (Sandbox Code Playgroud)

我不太确定还可以尝试什么。

小智 6

您可以通过在引号中写入窗口类型curses._CursesWindows来解决这个问题,如下所示:

import curses

def main(stdscr: 'curses._CursesWindow'):
    # now intellisense will provide completions :)
    pass

curses.wrapper(main)
Run Code Online (Sandbox Code Playgroud)