substitute for c/java's ?:

Remco Gerlich scarblac at pino.selwerd.nl
Thu Jun 14 02:26:16 EDT 2001


Jochen Riekhof <jochen at riekhof.de> wrote in comp.lang.python:
> Hi...
> 
> as a newcomer to python (like it a lot!) I found almost everything great
> except two things:
> 1. (most important)
> I am missing something like the c/Java ?: operator. This is so convenient in
> many places and saves a lot of typing.
> It works like
> result = option ? value1 : value2;
> which is equivalent to
> if option:
>     result = value1
> else:
>     resultl = value2
> 
> Is there anything I overlooked?

Not really. Just write the if:, it's more obvious what it does when you read
the code (especially when the expressions get longer).

> 2. switch (not important)
> if elif else is not a proper substitute for switches, as the variable in
> question has to be retyped in each if/elif clause.

For long statements, you could use a dictionary.

e.g.

switch(s) {
   case "whee": do_whee(); break;
   case "bla":  do_bla(); break;
   case "spam": do_spam(); break;
}

becomes

switch = {
   "whee": do_whee,
   "bla":  do_bla,
   "spam": do_spam
}
switch[s]()

You only need to initialize the dictionary once, can pass it to other
functions, etc.

But for only a few options, if: elif: isn't so bad.

-- 
Remco Gerlich



More information about the Python-list mailing list