You are likely already aware of most of Python’s inline greatness, like ternaries:

value = x if a > 10 else y

And comprehensions:

names = [ for e in employees]
capitals = {city.state : for city in capital_cities}

But there are a few more obscure (though none-the-less super-useful) ones that people don’t seem to know about.

Watch the magic unfold!

The power of if

Do you have annoyingly redundant code that looks like this, checking to see if a value exists and assigning a fallback if necessary?

important_key = provided_arg if provided_arg else default_key

Instead, write it like this!:

important_key = provided_arg or default_key

Look at that. Look at how many words you saved. 1

This is a very neat concept called a coalescing operator which is a fancy way of saying “first we check the first thing, and if that is false then we use the second thing.”

(It is important to note, if you’re familiar with this concept from C# or Perl, that Python’s or is not an actual null coalescing operator; it’s more of a ‘false coalescing operator’, which is a term I just made up. Put another way: in C#, 0 ?? 2 evaluates to 0; in Python, 0 or 2 evaluates to 2.)

(Inline) exception (handling), your honor!

I am willing to bet all of the money in my pockets 2 that you have oodles of code that looks like this:

    x = very_complicated_method()
except WeirdError:
    x = fallback_argument

Instead, write it like this:

x = very_complicated_method() except WeirdError: fallback_argument

Isn’t that nicer?

Wait, why does this matter?

Yes, you can make the argument that the mental effort you spend reading this post and remembering these shortcuts is greater than the effort you spend typing out the extra few keywords, but there’s something to be said for aestheticism 3. Ternaries are ugly. Unnecessary blocks are unnecessary.

Besides, if you can’t impress your friends and colleagues with arbitrary Python arcana, what’s the point of even being a programmer?

  1. You saved two words. [return]
  2. I have no money in my pockets. [return]
  3. I believe the hip way to say this is being Pythonic. [return]
Liked this post? Follow me!