Yaho Muse
Yaho Muse

Reputation: 45

Using a callback as an argument

I have a bit of trouble using a callback as an argument to a function. I am using a python package called keyboard which has a function called keyboard.add_word_listener() with required arguments of text and callback. The text is simply the word the function is looking for, and according to the docs, the callback is "is an argument-less function to be invoked each time the given word is typed." I have been passing a function through that argument that is essentially just printing things. To the best of my knowledge, this should run all of the code within the function whenever it detects the text is typed. However, it immediately runs the function, before I type anything, and when I actually do type the text, it gives the error 'NoneType' object is not callable. If anyone could tell me why this isn't working the way it should, that would be great. Minimum reproducible example:

import keyboard

stopKey = "Windows"


def test():
    print("Success!")

keyboard.add_word_listener("test", test())

running = True
while running:
    if keyboard.is_pressed(stopKey):
        running = False

As you can see, when you run the program, it immediately prints "Success!" and if you type "test" + space anywhere, it gives an error message.

Upvotes: 0

Views: 365

Answers (1)

Carlos Leite
Carlos Leite

Reputation: 302

dos not use parenthesis to pass the fucntion, you are "calling" it

keyboard.add_word_listener("test", test)  # no parenths

Upvotes: 2

Related Questions