views:

132

answers:

4

Here's the code I have now:

lang = window.get_active_document().get_language()
if lang != None:
    lang = lang.get_name()

Is there a better way to do that? I'm new to Pythonic and was wondering if there's a more Python way to say "something equals this if x is true, else it equals that."

Thanks.

+6  A: 

You could do lang = lang and lang.get_name() instead of the 'if' statement.

If lang is None it will stay None. If not, it will be set to lang.get_name().

I'm not sure if that syntax makes things much clearer, though.

P.S. Instead of lang != None you should use not lang is None.

Dingo
Thanks. Can you give a quick explanation? The syntax doesn't make much logical sense to me, and Googling for 'python and' doesn't get me anywhere.
Mike Crittenden
Mike, if X is false in the clause "X and Y" then the clause evaluates to false and Y is not evaluated. None evaluates to False, so in "lang and lang.get_name()" , if lang is None the clause returns false and get_name is never called, otherwise get_name is called. The clause returns the last value evaluated, so the return value of "get_name" comes back.
Steve B.
@Mike Crittenden, In Python, `and` always returns one of its arguments. If the first argument is true, it knows that the result depends wholly on the second argument's truth or falsehood so it just returns the second argument. If the first argument is false it short-circuits and returns the first argument. Similar things happen for `or`.As you point out, it isn't all that obvious or clear. In the case of replacing `is not None`, it can also be buggy. Personally, I never use `and` this way.
Mike Graham
Awesome, thanks guys.
Mike Crittenden
+2  A: 

Try

lang = lang.get_name() if lang else None
Sudhir Jonathan
@Sudhir, did you mean "lange" or "lang"? I'd correct it as a typo, but I'm not sure whether it was intentional or accidental.
Peter Hansen
I think it was 'lange' in the original question... I was wondering why too :D
Sudhir Jonathan
Yeah, I accidentally put lange at first.
Mike Crittenden
+2  A: 
try:
    lang = window.get_active_document().get_language().get_name()
except AttributeError:
    lang = None

The advantage here is that window itself and all three nested methods become guarded in one statement.

Kevin Little
+1  A: 

Your solution is fine and clearer most solutions offered so far. Slightly more pythonic would be:

lang = window.get_active_document().get_language()
if lang:
    lang = lang.get_name()

or

lang = window.get_active_document().get_language()
if lang is not None:
    lang = lang.get_name()
Mark Tolonen