I am trying in python to unpack some dict into some function:
I have a function that get packet
as parameter (that should be dict)
def queue(self, packet):
self.topic.publish(self.message, self.client, **packet)
and I call it this way:
queue({
'an_item': 1,
'a_key': 'value'
})
the publish function, is in 3rd party api (Google Pub/Sub API) and from what I looked at 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's accepting **attrs in order to pass all keyword parameters into another function.
Currently.. my queue() function isn't working.
How, if possible, can I fix my queue()
function to unpack the packet
dict argument into something publish()
will accept?
Thanks!
EDIT:
Some error messages I got.
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:
as @gall suggested correctly, it is the data I was sending and there is no problem with the unpacking. with this function:
def queue(self, packet):
self.topic.publish(self.message, self.client, **packet)
It works when I call it with strings only:
queue({
'an_item': '1',
'a_key': 'value'
})
Thank you all!
According to the docstring of publish, attr
must be a string -> string
dict.
You can fix the issue by replacing
queue({
'an_item': 1,
'a_key': 'value'
})
with purely string arguments, e.g.
queue({
'an_item': '1',
'a_key': 'value'
})
It seems your issue had nothing to do with dictionary unpacking.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With