Why ELIF?

Simon Forman sajmikins at gmail.com
Sun Oct 11 14:52:33 EDT 2009


On Sun, Oct 11, 2009 at 2:15 PM, TerryP <bigboss1964 at gmail.com> wrote:
> 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")
>
>

I'll often do that this way:

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

def no_cmd(*a, **b):
    raise SyntaxWarning("Syntax error in above program")

Commands.get(cmd, no_cmd)(args)



~Simon



More information about the Python-list mailing list