Search code examples
google-cloud-platformgoogle-cloud-pubsubgoogle-cloud-iot

Google Cloud Pub/Sub SDK - subscribe() takes at least 3 arguments (2 given)


The code below, to subscribe in a topic, was working some months ago.

from google.cloud import pubsub

def callback(message):
    print(message.data)
    message.ack()

project_id = "my_project"
topic_name = "xxx"
subscription_name = "xxx"

subscriber = pubsub.SubscriberClient()
topic = "projects/{}/topics/{}".format(project_id, topic_name)

subscription_name = 'projects/{}/subscriptions/{}'.format(project_id, subscription_name)

subscription = subscriber.subscribe(subscription_name)
future = subscription.open(callback)

try:
    future.result()
except Exception as ex:
    subscription.close()
    raise

I tried to run it now and I am getting the following error message:

File "pubsub_sub.py", line 16, in < module >
subscription = subscriber.subscribe(subscription_name)
TypeError: subscribe() takes at least 3 arguments (2 given)

As stated in the Google-Cloud Pub/Sub documentation, it seems my code is right. Also, as I said, this same code was working in the past. Any suggestion?


Solution

  • As explained in the docs, you're missing the callback.

    It does look like the README.rst on Github is wrong, since on the code we can see those 3 arguments are required:

    def subscribe(
            self, subscription, callback, flow_control=(),
            scheduler=None):
    

    I've just proposed a fix to the file for clarification.

    Edit:

    Regarding the fact that it previously worked, you can see in the repo how on pull 5237 subscribe_experimental was created, and this method required the callback, unlike the regular subscribe. Later on, on pull 5274, subscribe_experimental was promoted to subscribe, meaning that now the callback is required.

    If you're having errors when providing the callback, make sure all your libraries are up to date.