Article:
 |
|
Test-Driven Development in Python
|
| Subject: |
|
Why the code failed |
| Date: |
|
2005-03-30 19:33:11 |
| From: |
|
Gancho
|
|
|
Your code,
def matches(self, date):
return ((self.year and self.year == date.year or True) and
(self.month and self.month == date.month or True) and
(self.day and self.day == date.day or True) and
(self.weekday and self.weekday == date.weekday() or True))
failed the testMatchesFalse test because == binds more tightly than "or."
>>> c=1
>>> c and c == 2 or True
True
>>> c and c == (2 or True)
False
I agree that the explicit code is cleaner.
I'm just learning Python, and it's interesting that laziness is one of the three virtues in the Perl world yet is decried in Python circles.
|
Showing messages 1 through 1 of 1.
-
Why the code failed
2005-05-14 17:14:16
cpgray
[View]
The reason the code fails is that the simulation isn't exact. If a is True, "a ? b : c" returns b.
If a is True, "a and b or c" evaluates b. If b evaluates to True, evaluation stops and b is returned. If b evaluates to False (or None or 0 or [], etc.), evaluation continues and c is evaluated and returned. In other words, you'll never return b if b evaluates to False.
For example "1 == 1 and 2 or 3" returns 2 as expected, but "1 == 1 and 0 or 3" returns 3.