Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unpacking a dictionary and passing to a function as keyword parameters

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!

like image 506
ET-CS Avatar asked Nov 08 '22 19:11

ET-CS


1 Answers

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.

like image 68
Jonas Adler Avatar answered Nov 15 '22 06:11

Jonas Adler