Mike Crittenden
Mike Crittenden

Reputation: 5917

Is there a cleaner or more efficient to do this Python assignment?

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.

Upvotes: 0

Views: 250

Answers (4)

Sudhir Jonathan
Sudhir Jonathan

Reputation: 17526

Try

lang = lang.get_name() if lang else None

Upvotes: 2

Mark Tolonen
Mark Tolonen

Reputation: 177991

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()

Upvotes: 1

Kevin Little
Kevin Little

Reputation: 12976

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.

Upvotes: 2

Dingo
Dingo

Reputation: 3395

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.

Upvotes: 7

Related Questions