Error message

  • Notice: Trying to get property of non-object in filter_default_format() (line 532 of /home/ntroutman/webapps/nt_drupal/modules/filter/filter.module).
  • Notice: Undefined variable: options in filter_process_format() (line 911 of /home/ntroutman/webapps/nt_drupal/modules/filter/filter.module).

Chainned Comparisons, Generators, For-Else Loops and N-ary-Operators

So one of the coolest things I just found out about python is that it will let you chain comparisons, so 1 < a < 10 works. Even 1 < a < 10 < b < 25, and so on, you can even get really crazy and try a < 5 > b, wich is a funky way of saying a < 5 and b < 5, pretty cool huh!

The next thing I learned about are generator expressions. Thing list comprehensions but instead of returning a list it returns an interator. So instead of this which makes a temporay list:

for e in [x.capitalize() for x in l if 'bob' not in x]:
    print e

We can do this:

for e in (x.capitalize() for x in l if 'bob' not in x):
    print e

Granted these are examples, but you get the idea, no intermediary list, just an iterator. And its really simple, instead of surronding it in square brackes use pararentheses, thats the only difference.

Moving on, did you know you can follow a for-loop with an else statement? Yep, you can and the else block only gets executed if the for loop terminates normally, i.e. you didn't break out of it. How often do you write

match = True
for item in a_list:
    if someTestFunc(item):
        match = False
if match:
    # do something

Instead this could be:

for item in a_list:
    if someTestFunc(item):
    # do something

Pretty niffty heh! Last but not least is the N-ary operator, remember back in C and Java when you could write something like:

greeting = (person.male) ? 'Hello Sir!' : 'How do you do Madam?'

Then you came to python and it did not have a ternary operator which was sad so we wrote:

if person.male:
    greeting = 'Hello Sir!'
    greeting = 'How do you do Madam?'

Then we learned to be sneaky and started doing this:

greeting = person.male and 'Hello Sir!' or 'How do you do Madam?'

And finally Guido appeased us and added this syntax to python:

greeting = 'Hello Sir!' if person.male else 'How do you do Madam?'

But, did you know it can be chained, like so:

greeting = 'Hello Sir!' if person.male else 'Morning Miss' \
                if not person.married else 'How do you do Madam?'

Python gets cooler every day. Hope you learned something today about the power of python and never forget:

import antigravity


Add new comment