pythonurwid

Keypress Function in Python Urwid


Forgive me if this is not a good question. I'm having hard time understanding one of the codes in URWID library in Python. This is one of the example code in the tutorial. http://urwid.org/tutorial/index.html

 1 import urwid

 2 def exit_on_q(key):
 3   if key in ('q', 'Q'):
 4     raise urwid.ExitMainLoop()

 5  class QuestionBox(urwid.Filler):
 6    def keypress(self, size, key):
 7      if key != 'enter':
 8        return super(QuestionBox, self).keypress(size, key)
 9      self.original_widget = urwid.Text(
 10       u"Nice to meet you,\n%s.\n\nPress Q to exit." %
 11       edit.edit_text)

 12  edit = urwid.Edit(u"What is your name?\n")
 13  fill = QuestionBox(edit)
 14  loop = urwid.MainLoop(fill, unhandled_input=exit_on_q)
 15  loop.run()

My questions are

1) Keypress function takes keystrokes as the input. I couldn't understand in which line of the code, keystrokes are being assigned to 'key' variable. It is directly used without any initialization in line 7

    if key != 'enter':

How is this possible?

2) Keypress function has not been called outside the QuestionBox class. Even without calling the function, why it is getting executed?

3) There is no init function defined inside the new class QuestionBox. Why it is not needed? I believe it should have both init and super in class definitions.

4) what is the 'size' field in 'keypress' function?

Thanks in advance


Solution

    1. key is a parameter, so most likely whoever is calling the function is passing the most recently pressed key to it.
    2. Since you have passed fill to urwid.MainLoop, and QuestionBox is inherited from an urwid class called Filler, the likely explanation is that MainLoop is calling the function with the appropriate parameters. According to documentation (Your link): "In QuestionBox.keypress() all keypresses except ENTER are passed along to the default Filler.keypress() which sends them to the child Edit.keypress() method."
    3. If the constructor is not specified in a child class in Python, then the base class constructor is called automatically. Thus, neither init nor super are needed.
    4. As for the size parameter, the documentation is somewhat unclear on what it is, but looking further should turn up an answer.

    Update for #4:

    size is the size of the widget, although I am unsure what purpose this serves.