kwargs keyword evaluation

Carsten Haese carsten at uniqsys.com
Wed Feb 15 11:51:00 EST 2006


On Wed, 2006-02-15 at 11:40, tzellman at gmail.com wrote:
> Ok, so here is my situation:
> 
> Let's assume I have a function that makes good use of the kwargs
> parameter. It requires that there is a certain "format" for the kwargs
> keywords. (I am using Django, btw). The format is like such:
> "SOMEVAL__exact", etc., where SOMEVAL is some value that it parses from
> the keyword.
> 
> Now, I want to call this function, specifying the kwargs. The problem
> is that I want to dynamically set the kwargs. For example, I don't want
> to hard code in the name like such:
>     function_call(name__exact="Tom")
> 
> I want to generate the keyword on the fly. So, I want to do this:
> (assume someVar == 'name' for now)
> keyword = someVar + "__exact"
> 
> The problem:
> I need to know how to get it to use the VALUE of the keyword for the
> keyword.
> 
> 
> My thoughts:
> (1) Maybe I can override the kwargs parameter by doing such:
> function_call(kwargs={keyword:"Tom"})
> *loud buzzer* Nope. (as expected)
> 
> (2) Maybe I can just pass it in:
> function_call(keyword="Tom")
> Nope! (as expected, it tries to use 'keyword' as the keyword)

The correct answer is behind door number 3:

some_dict = {keyword: "Tom"}
function_call(**some_dict)

HTH,

Carsten.





More information about the Python-list mailing list