0

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.

1
  • 3
    test() is an immediate call of the function named test. Its return value (None) gets used as the callback. You need to pass test itself as the callback. Commented Aug 10, 2020 at 16:26

1 Answer 1

2

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

keyboard.add_word_listener("test", test)  # no parenths
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! So what would I do if I wanted to pass an argument in that function? Suppose I wanted keyboard.add_word_listener to call test("hi"), assuming I added that as a valid argument in the function?
a callback function may recieve parameters.... it can have parameters as just any normal function. YOu may sse this "caracterstics' a lot on jQuery for instance... All you have to do is to treate the parameter. But , the caller has to be prepare to "send" those parameters to the function. It doent means you use parenths...a Call back is like a function pointer (C) .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.