pep 336: Make None Callable

Steven Bethard steven.bethard at gmail.com
Thu Nov 4 00:49:38 EST 2004


The Eternal Squire <eternalsquire <at> comcast.net> writes:
> 
>      Before, checking function table entry against None:
> 
>          class Select:
> 
>              def a(self, input):
>                  print 'a'
> 
>              def b(self, input):
>                  print 'b'
> 
>              def c(self, input);
>                  print 'c'
> 
>              def __call__(self, input):
>                  function = { 1 : self.a,
>                           2 : self.b,
>                           3 : self.c
>                         }.get(input, None)
>                  if function:  return function(input)

Another possibility:

>>> class Select:
...    def a(self, input):
...        print 'a'
...    def b(self, input):
...        print 'b'
...    def c(self, input):
...        print 'c'
...    def __call__(self, input):
...        try:
...            return {1:self.a,
...                    2:self.b,
...                    3:self.c}[input](input)
...        except KeyError:
...            pass
...           
>>> Select()(1)
a
>>> Select()(2)
b
>>> Select()(3)
c
>>> Select()(5)

I find this one much more useful.  Rarely do I truly want a no-op if I get a
value that isn't in my dict, in which case there is something other than pass in
the except block.

Steve






More information about the Python-list mailing list