Valueerror: only callable can be used as callback

ValueError: Only callable can be used as callback

This error occurs when you try to use a non-callable object as a callback function in your code. In Python, a callable object is an object that can be called as a function. It can be a built-in function, a user-defined function, or an instance of a class that implements the `__call__` method.

The callback function is a function that is passed as an argument to another function and is executed at a specific point or in response to a certain event. This allows you to customize the behavior of a function by providing different callback functions.

Example 1:


def callback_function():
    print("This is a callback function")

def main_function(callback):
    callback()

main_function(callback_function) # Output: "This is a callback function"
  

In this example, we define a callback function `callback_function` that prints a message. Then, we define a `main_function` that takes a callback as an argument and executes it. We pass our `callback_function` as the argument and it successfully executes, resulting in the desired output.

Example 2:


class CallbackClass:
    def __call__(self):
        print("This is a callback function")

def main_function(callback):
    callback()

callback_instance = CallbackClass()
main_function(callback_instance) # Output: "This is a callback function"
  

In this example, we define a class `CallbackClass` that implements the `__call__` method. This allows instances of the class to be called as functions. We create an instance of `CallbackClass` called `callback_instance` and pass it as the callback to the `main_function`. The `main_function` executes the callback, resulting in the desired output.

Now, if you encounter the “ValueError: Only callable can be used as callback” error, it means that you are trying to use a non-callable object as a callback. Make sure that the object you are passing as a callback is a function or an object that can be called like a function.

Same cateogry post

Leave a comment