Why ELIF?

TerryP bigboss1964 at gmail.com
Sun Oct 11 20:15:06 CEST 2009


On Oct 11, 3:42 pm, Esmail <ebo... at hotmail.com> wrote:
> cool .. I hadn't seen that. Not working quite at the 'pythonic' level yet
> I am not sure I think it's more readable that the if statement. Also, curious
> if the dictionary approach is more efficient.
>

Somehow I doubt that "Look up X in dictionary D" could ever be more
efficient (in terms of space and time, at least) then "Check if X is
equal to Y". It's not about what you get in runtime but what you get
in monkey time.


Most expressions that would make someone reach for a C-like switch()
statement can be expressed with dictionaries or attributes instead.

Here is a dorks approach to calling a specific function with arguments
based on a command:

  args = re.split('\s', line)
  cmd  = args.pop(0)

  if cmd == "ham":
      ...(args)
  elif cmd == "spam":
      ...(args)
  elif cmd == "eggs":
      ...(args)
  else:
      raise SyntaxWarning("Syntax error in above program")

Here is more of a look up table approach:

Note: let Commands be a dictionary, such that { "ham" : ...,
"spam" : ..., "eggs" : ... }.

  args = re.split('\s', line)
  cmd  = args.pop(0)

  if cmd in Commands:
      Commands[cmd](args)
  else:
      raise SyntaxWarning("Syntax error in above program")


What values does this second approach offer over the first one? The
most obvious one is that the program does more of the work, then the
maintenance programmer. In a more Object-Oriented light, you could
also fetch a member of an object at run time, and use that in place of
a dictionary. Take a look how the standard 'cmd' module dispatches
stuff.



I might take flak here, for writing something like 'dict[key]
(func_args)' instead of something more Pythonic, but the code serves
to express a point, not teach a system of branch of Zen :-P.

--
  TerryP.
Just Another Programmer.



More information about the Python-list mailing list