Automatic binding of **kwargs to variables

Mike Meyer mwm at mired.org
Sun Oct 30 01:18:43 EST 2005


"lbolognini at gmail.com" <lbolognini at gmail.com> writes:
> Peter Hansen wrote:
>> Do you mean this instead?
>>
>>       elif name in expected_form1_kwargs and name not in kwargs:
>>
>> What you wrote doesn't do what you think it does...  it actually tests
>> for whether True or False is a key in kwargs, depending on whether "name
>> in expected_form1_kwargs" returns True or False.
>
> Hi Peter,
>
> you're right... the code needed also other fixes and I didn't find a
> way to do it other than this:
>
> def foo(**kwargs):
>     expected_form1_kwargs = ["arg1", "arg2"]
>
>     for name in expected_form1_kwargs:
>         if name not in kwargs:
>             kwargs[name]=None
>
>     for name in kwargs:
>         if name in kwargs and name not in expected_form1_kwargs:
>             raise ValueError, "Unrecognized keyword: " + name
>
>     print kwargs


You're contorting things horribly, and - not unexpected when you do
that kind of thing - running code that has no effect. To wit, the
second loop goes through every key in kwargs. The first thing it does
is test to see if the key you just selected from kwargs is in
kwargs. This test is always true.

IIUC, the reason you're going through these contortions is that the
argument list is long and repeated in a number of different places. So
you're going to declare expected_form1_kwargs in one place and use it
repeatedly. Presumably, you can also bundle the set/check code up in a
function that you pass kwargs to as well.

Have you thought about generating the more readable form from code you
write? One of the most powerful tools available to programmers is code
that writes code. This seems to be the perfect case for such a
tool. You could, for instance, run your code through m4 to generate
the Python that actually gets run. A trivial script that looks for
"^def " and then replaced **kwargs with your list could serve as a
custom preprocessor.  To be particulary perverse, you could try using
a Cheetah template to generate your code - I've not tried generating
Python with it, but it creates Makefiles quite nicely.

       <mike
-- 
Mike Meyer <mwm at mired.org>			http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.



More information about the Python-list mailing list