pythonenumspynput

How to get enum value


from pynput.keyboard import Key
from pynput.mouse import Button
from enum import Enum

value=Key.esc
def corresponding_event(key):
    print(type(key))
corresponding_event(value)

produces <enum 'Key'>

How would I obtain the value for the enum 'Key'and also check if it's an enum the function can pass different type of values as well. <enum 'Button'> ,<enum 'Key'> ,<class 'str'> ,<class 'int'>

I know you can check for enums with

if isinstance(key,Enum):
    print(key.name,key.value)

I would like to do different actions if it's a key or button.


Solution

  • You can just check for it with isinstance

    from enum import Enum
    
    
    class Key(Enum):
        a = 1
        b = 2
        c = 3
    
    
    class Button(Enum):
        a = 10
        b = 20
        c = 30
    
    
    def some_func(x):
        if isinstance(x, Key):
            print('Key', x.value)
        if isinstance(x, Button):
            print('Button', x.value)
    
    
    k = Key(1)
    b = Button(20)
    
    some_func(k)
    some_func(b)
    

    If your function can get all sorts of different types and you need to do things depending on the type you need to check for types, no real way around it.

    I am not sure what your exact questions is, but form what you wrote just checking via isinstance(x, Key) and isinstance(x, Key) is what you want, getting the value form an enum is also just .value. So in general you already more or less wrote what you need.