Unpacking a dictionary and switching to a function as keyword parameters

I am trying in python to unpack some dict into some function:

I have a function that gets packetas a parameter (which should be a dict)

def queue(self, packet):
    self.topic.publish(self.message, self.client, **packet)

and I call it like this:

queue({
        'an_item': 1,
        'a_key': 'value'
    })

the publishing function is in a third-party api (Google Pub / Sub API) and from what I looked at the source:

def publish(self, message, client=None, **attrs):
    ...
    message_data = {'data': message, 'attributes': attrs}
    message_ids = api.topic_publish(self.full_name, [message_data])

it takes ** attrs to pass all the keyword parameters to another function.

My queue () function is currently not working.

How, if possible, can I fix my function queue()to unpack the packetdict argument into something publish()will take?

Thank!


EDIT:

Some error messages I received.

for

def queue(self, packet):
    self.topic.publish(self.message, self.client, **packet)

I get: TypeError: 1 has type <class 'int'>, but expected one of: (<class 'bytes'>, <class 'str'>)


for

def queue(self, packet):
    self.topic.publish(self.message, self.client, packet)

I get: publish() takes from 2 to 3 positional arguments but 4 were given


for

def queue(self, **packet):
    self.topic.publish(self.message, self.client, packet)

I get: TypeError: queue() takes 1 positional argument but 2 were given


and for:

def queue(self, *packet):
    self.topic.publish(self.message, self.client, packet)

I get: TypeError: publish() takes from 2 to 3 positional arguments but 4 were given


EDIT 2:

@gall , , , . :

def queue(self, packet):
    self.topic.publish(self.message, self.client, **packet)

, :

queue({
        'an_item': '1',
        'a_key': 'value'
    })

!

+4
1

docstring , attr string -> string dict.

,

queue({
    'an_item': 1,
    'a_key': 'value'
})

,

queue({
    'an_item': '1',
    'a_key': 'value'
})

, .

+1

Source: https://habr.com/ru/post/1681120/


All Articles