Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

More and more I find myself doing these kinds of operations:

result = this_variable and this_variable[0].operation()

Or:

result = search or make_something()

My only concern is that it might blur the logic of the function and was looking for some info on how pythonic is this or how it should be implemented instead.

share|improve this question

2 Answers 2

Readable code is usually considered pythonic. While this may seem foreign if Python is a second language, once you understand how the logical, coalescing operators work it becomes quite readable; therefore, I would say this is indeed pythonic.

I've seen this used all over, and prefer to use it myself. The alternative is to nest two assignment operations inside of an if..else. This has always seemed counter-intuitive to me, because you're assigning a value to the same variable, but you must use two assignment operators. This is neither minimalist or readable, and therefore not pythonic.

As a side note, I often find myself missing these operators when I use other languages. I typically explain this behavior with the analogy "like Python's or operator".

share|improve this answer

result = this_variable and this_variable[0].operation()

What happens if this_variable is empty? you are left with result = [] (assuming it was a list). That makes no sense. Are you interested in the AND operation of these two values? not really, what you really want is the result of this_variable[0].operation(), only that before you need to make sure this_variable is not empty. So a more declarative code (which also has a more sensible result when this_variable is empty), would be:

result = (this_variable[0].operation() if this_variable else None)

result = search or make_something()

Here you want result to be the value search or, if this is falsy, the output of make_something(). So this code is ok, perfectly declarative. You could write it with a conditional expression (as any other boolean expression) but they are usually not as clear.

share|improve this answer
    
Your right @tokland the idea with the and is to see if the variable exists and if it does do something else just keep the empty variable. I didn't know this could be made any other way and thanks for your answer I think it's cleared and cleaner for this case. –  user1634074 May 31 '13 at 21:24

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.