tags:

views:

200

answers:

3

Looking for the python equivalent of this.

http://ca3.php.net/manual/en/function.extract.php

+3  A: 

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!
SilentGhost
def __api_call__(self, method, resource, **kwargs): # do stuffdef do_call(my_dict): self.__api_call__('POST', '/api/foobar/', <my_dict to args here>)Is there a better way to do what I am thinking - don't want to change __api_call__'s use of kwargs.
ashchristopher
+8  A: 

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
Paolo Bergantino
+1  A: 

One generally uses locals() to achieve this result, but the exact functionality is up to you.

>>> print apple
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
NameError: name 'apple' is not defined
>>> print banana
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
NameError: name 'banana' is not defined

>>> variables = {"apple" : "a rigid, juicy fruit", "banana" : "a soft, fleshy fruit"}
>>> for variable,value in variables.iteritems():
...  locals()[variable] = value
... 
>>> print apple
a rigid, juicy fruit
>>> print banana
a soft, fleshy fruit

EDIT

Thanks to everyone who has diligently commented on the badness of this approach. I wholeheartedly agree that THIS IS A BAD APPROACH, and it deserves to be mentioned in the actual response for anyone who stumbles across this page. (Never underestimate that; I saw this technique in a code snippet somewhere. I can see why in that particular case it was harmless, but I know I can't go around encouraging bad methodology just because there are situations in which it won't break.)

David Berger
The Python docs say about locals(): "The contents of this dictionary should not be modified; changes may not affect the values of local variables used by the interpreter." http://docs.python.org/library/functions.html Furthermore, code that uses locals() is generally pretty unpythonic; there's almost always a better way to write things.
Miles
Not downvoting as this was an honest attempt to answer the question, but: don't ever do this.
Carl Meyer