[Tutor] Passing perimeters in dictionary values?

Kent Johnson kent37 at tds.net
Tue Feb 24 20:45:02 CET 2009


On Tue, Feb 24, 2009 at 2:35 PM, spir <denis.spir at free.fr> wrote:
> Le Tue, 24 Feb 2009 14:03:09 -0500,
> nathan virgil <sdragon1984 at gmail.com> s'exprima ainsi:

>> so that I can call methods from a dictionary, instead of having an
>> excruciatingly long if structure. Unfortunately, the problem I'm running
>> into with this is that I can't pass any perimeters through the dictionary. I
>> can't figure out how, for example, I could have an option that calls
>> crit.eat(2) and another that calls crit.eat(4). The only thing I can think
>> of is going back to the if structure, but my instinct tells me that this is
>> a Bad Idea. What can I do?
>
> There is a syntactic trick for this, commonly called *args. You can call a function and pass it a variable holding a 'pack' of arguments prefixed with '*' so that the args will be automagically unpacked into the call message. Below an example:
>
> def sum(a,b):
>        return a+b
> arg_list = (1,2)
> func_calls = {1:sum(*arg_list)}
> print func_calls[1]
> ==> 3
>
> Like if I had written sum(1,2) -- except that the arg_list can now be unknown at design time!

I don't think this is addressing the OP's question. Your dict will
contain the result of calling sum(1, 2). He wants a callable which he
can call later.

Kent


More information about the Tutor mailing list