[Tutor] Dict of function calls

Steven D'Aprano steve at pearwood.info
Wed Sep 22 23:50:16 CEST 2010

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 :)

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

(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:


where name is "foo" or "bar", and args is anything you need to pass to 
the do() method.

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

Steven D'Aprano 
Operations Manager 
Cybersource Pty Ltd, ABN 13 053 904 082 
Level 1, 130-132 Stawell St, Richmond VIC 3121 
Tel: +61 3 9428 6922   Fax: +61 3 9428 6944 
Web: http://www.cybersource.com.au 

More information about the Tutor mailing list