pythoncoordinatescursescoordinate-systemspython-curses

What are the `y` and `x` params to the python curses `window.getch()` method?


I may be missing something very obvious, but I am confused by the optional [y, x] parameters to the window.getch( [y, x] ) method described in the Python documentation. What are these optional params for, and what do they do if I include them in my call?

As far as I can tell the documentation doesn't mention what these parameters are for. It just says:

Get a character. Note that the integer returned does not have to be in ASCII range: function keys, keypad keys and so on are represented by numbers higher than 255. In no-delay mode, return -1 if there is no input, otherwise wait until a key is pressed.

The window.get_wch( [y, x] ) and window.getkey( [y, x] ) methods seem to have similarly undescribed optional [y, x] params.


Solution

  • I had to go to the old curses library man pages to find an answer. The extra arguments move the cursor to the specified position. The thing I didn't realize is that these methods are not always just reading keyboard input. They can also modify the screen state, which is not at all obvious from the documentation. In the (not typically used) echo mode, these curses functions echo the keyboard input back to the screen.

    Older versions of the curses man page for example, say:

    Unless noecho has been set, then the character will also be echoed into the designated window according to the following rules: If the character is the current erase character, left arrow, or backspace, the cursor is moved one space to the left and that screen position is erased as if delch had been called. If the character value is any other KEY_ define, the user is alerted with a beep call. Otherwise the character is simply output to the screen.

    And then the netbsd man page for https://man.netbsd.org/curses_input.3 further describes the behavior of the mvgetch() function as:

    The mvgetch() and mvwgetch() functions are the same as the getch() and wgetch() functions, respectively, excepting that wmove() is called to move the cursor to the position specified by y, x before the character is read.

    So, if noecho is unset, then the Python getch() method with no params calls the C getch() function, and the key read from the keyboard is echoed at the current screen location. If the Python getch( y, x ) method is called with the optional y and x params, then the C mvgetch( y, x) function is invoked, which moves the cursor to y, x, and then does getch().

    Here is the code for _curses_window_getch_impl() in the curses Module of the cpython interpreter where we can see that that wgetch() or mvwgetch() are getting called depending on whether the optional params are provided: https://github.com/python/cpython/blob/main/Modules/_cursesmodule.c#L1401