Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

It there an equivalent to PHP's extract in Python? [duplicate]

Tags:

python

php

Looking for the python equivalent of this.

http://php.net/extract

like image 720
ashchristopher Avatar asked Jul 14 '26 15:07

ashchristopher


2 Answers

Maybe you would be better off explaining what you are trying to do. Any solution to the direct question would be rather unpythonic as there is almost certainly a better way to do what you want.

EDIT (per your comments):

And indeed, there is a better way.

What you are trying to do is known as unpacking argument lists, and can be done like this:

self.__api_call__('POST', '/api/foobar/', **mydict) 

A working example:

>>> def a_plus_b(a,b):
...     return a+b
... 
>>> mydict = {'a':3,'b':4}
>>> a_plus_b(**mydict)
7

And it also works with kwargs, as you might expect:

>>> def a_plus_b(**kwargs):
...     return kwargs['a'] + kwargs['b']
... 
>>> a_plus_b(**mydict)
7    
like image 141
Paolo Bergantino Avatar answered Jul 16 '26 03:07

Paolo Bergantino


no. why do you need it?

do the following (see comment)

def __api_call__(self, method, resource, **kwargs):
    print(kwargs)

def do_call(my_dict):
    self.__api_call__('POST', '/api/foobar/', **your_dict)   # double asterisk!
like image 41
SilentGhost Avatar answered Jul 16 '26 05:07

SilentGhost