[Tutor] Dict of function calls

Pete pkoek11 at xs4all.nl
Thu Sep 23 01:21:27 CEST 2010


On 2010-09-22, at 5:50 PM, Steven D'Aprano wrote:

> On Thu, 23 Sep 2010 06:07:21 am Pete wrote:
>> For a plugin mechanism, I'm populating a dict with calls to the
>> implemented plugins.
> [...]
>> Now I get that I need to instantiate foo and bar first before I can
>> refer to them in the dict.
>> 
>> so something like
>> 
>> foo_instance = foo()
>> bar_instance = bar()
>> 
>> list = { 'foo': foo_instance.do(), 'bar': bar_instance.do() }
>> 
>> would probably work. But is that the best/pythonic way to do it?
> 
> (1) It's generally a bad idea to "shadow" the name of a built-in 
> function like list. Particularly since your variable list isn't 
> actually a list, but a mapping of name:function. Find a better 
> name :)

That was just for the example, of course, but point taken :)

> (2) You end up calling the do() methods inside the dict. You probably 
> mean to save the method itself as a callback function.

I did.

> (3) There's no need to keep the instances floating around as 
> independent names, unless you need direct access to them.
> 
> Putting these together, we get:
> 
> dispatch_table = { 'foo': foo().do, 'bar': bar().do }
> 
> Which you then later call using:
> 
> dispatch_table[name](args)
> 
> where name is "foo" or "bar", and args is anything you need to pass to 
> the do() method.

I see. And are those methods then unbound? (Because when instantiating the object it needs to do some initialization of instance variables,
and I think those were not available when calling an unbound method. (My understanding of the bound/unbound method distinction is rather vague at this point,
I apologise)

> Oh, and (4)... in Python circles, it's traditional but not compulsory 
> to use metasyntactic variables named after Monty Python sketches 
> rather than foo and bar. So spam, ham, eggs, parrot (dead or 
> otherwise), names of cheeses, aardvark..., although there is no 
> standard order.
> 
>  Indeed, when I design my killer language, the identifiers "foo" and
>  "bar" will be reserved words, never used, and not even mentioned in
>  the reference manual. Any program using one will simply dump core
>  without comment. Multitudes will rejoice. -- Tim Peters, 29 Apr 1998

THANK YOU! 

It's this kind of knowledge that I crave, sir.

:)

- Pete


More information about the Tutor mailing list