bmello
bmello

Reputation: 1984

What is recommended coding style for conditional operator in Python?

The following line is part of my code. I may be wrong, but it seems to be pythonic enough to me. However it is not clear, at first sight, what exactly it means. Is there a better code layout that would make it clearer? _idName is either a function or a DataFrame.

while  id1!="cancel" and ((id1 not in _idName.id.values) 
        if isinstance(_idName,_pd.DataFrame) else (_idName(id1) is None)):
    do something with the variables evaluated in the condition

Upvotes: 2

Views: 574

Answers (2)

jonrsharpe
jonrsharpe

Reputation: 121987

The layout of your code does indeed make it pretty unclear what's going on.

At a minimum, I would be inclined to line break after the binary operators and and or, per the style guide, rather than in the middle of a single condition.

I would also try to keep a ternary on a single line, where possible; in this case that ends up being quite long, though, so probably not an option. I think the boolean operators in the ternary make more sense at the start of their line, although I can't find a reference for this (beyond "Martijn likes it too").

One more readable example:

while (id1 != "cancel" and 
       ((id1 not in _idName.id.values) if isinstance(_idName, _pd.DataFrame) 
        else (_idName(id1) is None))):

or perhaps:

while (id1 != "cancel" and 
       ((id1 not in _idName.id.values)
        if isinstance(_idName,_pd.DataFrame)
        else (_idName(id1) is None)):

Upvotes: 3

Cyphase
Cyphase

Reputation: 12002

Create a small function that does the checking for you, then use that in the while statement.

def check_whatever(id1, _idName):
    if id1 == 'cancel':
        return False

    if isinstance(_idName,_pd.DataFrame):
        return id1 not in _idName.id.values:
    else:
        return _idName(id1) is None


while check_whatever(id1, _idName):
    do_stuff()

Upvotes: 1

Related Questions