substitute for c/java's ?:

Glyph Lefkowitz glyph at twistedmatrix.com
Thu Jun 14 05:20:30 EDT 2001


On Wed, 13 Jun 2001, Neil Macneale wrote:

> In article <9g5fc4$m8u$01$1 at news.t-online.com>, "Jochen Riekhof"
> <jochen at riekhof.de> wrote:
> 
> > I am missing something like the c/Java ?: operator.
> 
> The ?: operator is overrated. For the time you save typing, you
> are wasting someone else's because they need to figure out what you were
> thinking.

Trust me, this is true.  Compare the following actual examples:

        public static final String aan(String s)
        {
                char x = s.charAt(0);
                
                return ((( x == 'a')
                          ||
                         (x == 'e')
                          ||
                         (x == 'i')
                          ||
                         (x == 'o')
                          ||
                         (x == 'u')
                          ||
                         (x == 'A')
                          ||
                         (x == 'E')
                          ||
                         (x == 'I')
                          ||
                         (x == 'O')
                          ||
                         (x == 'U'))
                          ? "an " : "a "
                         );
        }


def aan(name):
    """Utility which returns 'a' or 'an' for a given noun.
    """
    if string.lower(name[0]) in ('a','e','i','o','u'):
        return 'an '
    else:
        return 'a '


Now, if you're getting paid per line of code, I could see how the first
example works better for you... but this was the *least* convoluted use of
the ? operator in all of the code that I could find; and I think it's
pretty clear which approach looks nicer.

> > if elif else is not a proper substitute for switches, as the variable in
> 
> I have found that using a dictionary of function pointers sometimes gives
> the switch statement feel.  For example, point to constructors...
> 
> cases = {"dog": Dog, "cat": Cat, "rabbit": Rabbit}
> 
> def createPet(type="cat"):
>     if casses.has_key(type): return casses[type]() #Good input...
>     else: return None   # bad input, or 'default' in C/java

The idiom that I've come to particularly like in Python, given a case like
that:

class PetShop:
  def pet_cat(self, name):
    ...
  def pet_dog(self, name):
    ...
  def pet_dinosaur(self, name):
    ...
  def buyPet(name="pooky", petType="cat"):
    petFunc = getattr(self, "pet_%s" % petType, None)
    if petFunc:
      return petFunc(name)
    else:
      # 'default' case mentioned above; usually raise something
 
> The above code is generally hard to read, so use sparingly and comment 
> well.  The thing I like about it is that the keys can be of any type. One
> problem is that all the functions called are going to need similar
> parameters,  but sometimes its a usefull trick.

If you use the specially-named-methods approach, it's almost
self-documenting!  I use this all over the place and I really like the way
it helps to organize code (it also makes testing easier, since each method
can be tested separately). It's like you can invent your own "adjectives"
to describe methods.

try-doing-*that*-in-java-ly y'rs,

                      ______      __   __  _____  _     _
                     |  ____ |      \_/   |_____] |_____|
                     |_____| |_____  |    |       |     |
                     @ t w i s t e d m a t r i x  . c o m
                     http://twistedmatrix.com/users/glyph






More information about the Python-list mailing list