This is a mirror of official site: http://jasper-net.blogspot.com/

Python Tricks and Hints

| Sunday, July 24, 2011
This is a small collection of various tricks and hints that I have stumbled across while programming in Python. Some are trivial, and some are a bit more tricky. Feel free to steal shamelessly from this collection. :-)

Contents

  1. Emulating "?:"
  2. Checking the Python version
  3. Debugging CGIs
  4. Parallel sorting of lists
  5. Normalizing a MAC address
  6. Sorting IP addresses
  7. Parsing command line options
  8. Mixing Python and shell scripts
  9. Converting signal numbers to names
1. Emulating "?:"

    Python doesn't know the trinary operator "?:" from C. However, it's pretty easy to emulate:

    x ? y : z    -->    [z, y][bool(x)]

    (If you're sure that x is already a boolean type (or an integer of value 0 or 1), you can omit the bool() function, of course.)

    How does the trick work? We simply create a small list constant, containing the two values to choose from, and use the boolean as an index into the list. "False" is equivalent to 0 and will select the first element, while "True" is equivalent to 1 and will select the second one.

    Note that always all three operands will be evaluated, unlike the "?:" operator in C. If you need shortcut evaluation, use an if-else statement.

    Actually, there's another way to do it with shortcut evaluation, but it only works if y does not contain a boolean False equivalent:

    x ? y : z    -->    bool(x) and y or z


Read more: Python Tricks and Hints
QR: tricks.hawk

Posted via email from Jasper-net

0 comments: