-4

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.

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
DoubleS
  • 129
  • 1
  • 7
  • @MechanicPig What if `copy` or `delete` functions return `None` – codester_09 Sep 15 '22 at 14:53
  • 2
    `and` already works as you want, assuming both functions return truthy or falsey values…!? – deceze Sep 15 '22 at 14:54
  • @MechanicPig That’s the *opposite* of what OP wants. It’s also horribly unreadable. – Konrad Rudolph Sep 15 '22 at 14:54
  • @KonradRudolph This is not the opposite. I just mistakenly thought that OP wanted to avoid short circuit. – Mechanic Pig Sep 15 '22 at 14:57
  • @MechanicPig I mean, it exactly inverts OP’s requirement (OP wants short-circuiting, their code already does short-circuiting, and your suggestion *specifically* removes short-circuiting). That sounds like the opposite to me. – Konrad Rudolph Sep 15 '22 at 14:59

2 Answers2

4

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)

st4rk111er
  • 91
  • 3
1

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
JohnFrum
  • 343
  • 2
  • 9