'How to get rid of TypeError?

Currently working on implementing Google Cloud storage on Raspberry Pi. Whenever I run my code, I get the error:

TypeError: callback() takes 0 positional arguments but 1 was given

This is my code:

from google.cloud import pubsub_v1
import json
import datetime
import time

project_id = "projectid"
topic_name = "topic"

publisher = pubsub_v1.PublisherClient()
topic_path = publisher.topic_path(project_id, topic_name)

futures = dict()

def get_callback(f, data):
    def callback():
        try:
            futures.pop(data)
        except:
            print("Please handle {} for {}.".format(f.exception(), data))
    return callback

while True:
    time.sleep(3)
    text = "Hello Google"
    data = {"text":text}
    print(data)
    
    future = publisher.publish(topic_path, data=(json.dumps(data)).encode("utf-8"))
    future.add_done_callback(get_callback(future, data))
    time.sleep(5)

while futures:
    time.sleep(5)
    
print("Published message with error handler")

Any advice on how to solve said issue? :)



Solution 1:[1]

The callback function set by "add_done_callback" is called with an argument (the future itself), but it is defined without any.

Changing your callback creation to:

def get_callback(f, data):
    def callback(future):
        ...

should solve the problem.

See: https://cloud.google.com/python/docs/reference/pubsub/latest/google.cloud.pubsub_v1.publisher.futures.Future#google_cloud_pubsub_v1_publisher_futures_Future_add_done_callback

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 crystalAhmet