Define the order of terms in and logical operator

Viewed 35

suppose that I have the two functions below:

def copy(src, dst) -> bool
    "copy src to dst return True if succeed else False"

def delete(src) -> bool
    "delete src return True if succeed else False"

src and dst can be complicated Objects, not just generic. the code is implemented correctly.

using those two functions I would like to implement move() function and return true if only both succeeded:

def move(src, dst) -> bool 
    return copy(src, dst) and delete(src)

the order of the terms in the and statement is important since I cannot delete src object before copying it.

is there any way of defining in the and (or any other logical operator) to do first the copying and then the deletion? does the order matters?

p.s: I know that I can do it like this:

def move(src, dst) -> bool 
    b1 = copy(src, dst)
    b2 = delete(src)
    return b1 and b2

but, I would like to do it as a one-liner as shown.

2 Answers

The and operator already evaluates arguments left-to-right. It's also a short-circuit operator i.e. it only evaluates the right argument if the left one is true (since if it was false then the expression would return false whatever the right argument is)

I may have misunderstood you, but Python's and operator will shortcut the evaluation so that if you have func1(action) and func2(action) then func2(action) will only be called if func1(action) returns True. If it returns False, then func2(action) is not called.

Also, the functions are called in the order in which they appear in the and statement.

Example:

>>> def f1(action):
...     print(action)
...     return True
...
>>> def f2(action):
...     print(action)
...     return False
...
>>> f1("func1") and f2("func2")
func1
func2
False
>>> def f1(action):
...     print(action)
...     return False
...
>>> f1("func1") and f2("func2")
func1
False
Related