r/pythonhelp • • Nov 03 '22

Can't enter this SIMPLE case in a match statement

def on_press(key):
print(type(key))
x = str(key)
print (x, type(x))
match x:
    case 'w':
        print("stop")
        etc...

Output after pressing the 'w' key:

<class 'pynput.keyboard._win32.KeyCode'>
'w' <class 'str'>

No "stop" is printed, so it fails to enter the match case.

3 Upvotes

4 comments sorted by

1

u/Goobyalus Nov 03 '22

You're matching the _win32KeyCode object against a string. Convert to string, then match.

1

u/Auklin Nov 04 '22

Can you look at the question again and tell me what you mean

1

u/Goobyalus Nov 04 '22

Yeah, my bad.


str(key) is "'w'", not "w".

Print repr(obj) in the future to see it better.


You can use key.char (not all keys have the char property).

You can match key against keyboard._base.KeyCode(char="w")

1

u/AmongstYou666 Nov 03 '22

# if python version < 3.10
def do1():
    print("one stuff")
def do2():
    print("two things")
Case = {1: 'do1()', 2: 'do2()'}
inp = int(input("Choose 1 or 2: "))
try:
    eval(Case[inp])
except KeyError:
    print("Not a valid choice")