Are these two python statements the same?

1.6k views Asked by At

I have these two statements

return self.getData() if self.getData() else ''

and

return self.getData() or ''

I want to know are they same or there is any difference

4

There are 4 answers

1
mike.k On BEST ANSWER

I would say No because if self.getData() changes something during its operation, then the first statement has the possibility of returning a different result since it will make a 2nd call to it.

5
James Mills On

Maybe, but only if self.getData() is a pure function and has no side effects. More importantly the object that self.getData() returns must also be free of any side effects and consistently return a boolean value.

In the simplest case if f() is defined as:

def f():
    return ["Hello World!"]

Then the following:

x = f() if f() else ""

is logically equivalent to:

x = f() or ""

Since f() is treated as a boolean expression in both cases and f() will evaluate to a True(ish) or False(ly) value both expressions will return the same result.

This is called Logical Equivalence

In logic, statements p and q are logically equivalent if they have the same logical content. This is a semantic concept; two statements are equivalent if they have the same truth value in every model (Mendelson 1979:56). The logical equivalence of p and q is sometimes expressed as p \equiv q, Epq, or p \Leftrightarrow q. However, these symbols are also used for material equivalence; the proper interpretation depends on the context. Logical equivalence is different from material equivalence, although the two concepts are closely related.

0
hajtos On

The only difference I see is that the first one will call self.getData() twice, with the first one being used to evaluate boolean value and the second may be returned(if the first evaluated to True).

The other option will evaluate the function only once, using it both as boolean checking and returning.

This can be crucial if, for example, self.getData() deletes or modifies the data after returning it or the function takes long to compute.

1
Eli Rose On

They will have the same result, since both treat self.getData()'s result in a boolean context, but beware:

1) return self.getData() if self.getData() else ''

will run the function getData twice, while

2) return self.getData() or ''

will only run it once. This can be important if getData() takes a while to execute, and it means that 1) is not the same as 2) if the function getData() has any side effects.

Stick with 2).