[Python-ideas] bool(datetime.time(0, 0))

Steven D'Aprano steve at pearwood.info
Tue May 8 07:42:49 CEST 2012


On Tue, May 08, 2012 at 01:57:13PM +1000, Nick Coghlan wrote:
> On Tue, May 8, 2012 at 12:57 PM, Ethan Furman <ethan at stoneleaf.us> wrote:
> > The behavior is broken.  Midnight is not False.
> 
> Whereas I disagree - I see having zero hour be false as perfectly
> reasonable behaviour (not necessarily *useful*, but then having all
> time objects report as True in boolean context isn't particularly
> useful either).

On the contrary, it can be very useful to have all objects of some 
classes treated as true. For example, we can write:

mo = re.search(a, b)
if mo:
    do_something_with(mo)

without having to worry about the case where a valid MatchObject happens 
to be false.

Consider:

t = get_job_start_time()  # returns a datetime.time object, or None
if t:
    do_something_with(t)


Oops, we have a bug. If the job happens to have started at exactly 
midnight, it will wrongly be treated as false.

But wait, it's worse than that. Because it's not actually midnight that 
gets treated as false, but some arbitrary time of the day which depends 
on your timezone. It's only midnight if you don't specify a tzinfo, or 
if you do and happen to be using GMT.

Midnight (modulo timezone) is not special enough to treat it as a false 
value. It's not an empty container or mapping, or the identity element 
under addition, or the only string that contains no substrings except 
itself. It's just another hour.

(Midnight is only special if you care about the change from one day to 
another. But if you care about that, you're probably using datetime 
objects rather than time objects, and then you don't have this problem 
because "midnight last Tuesday" is not treated as false.)

I believe that having time(0,0) be treated as false is at best a 
misfeature and at worst a bug. It is as unnecessary a special case as it 
would be to have the string "\0" treated as false.

The only good defence for keeping it, in my opinion, would be fear that 
there is working code that relies on this.


> In matters of opinion, the status quo reigns.

That's somewhat of an exaggeration. The mere existence of a single 
dissenting opinion isn't enough to block all progress/changes. (Not 
unless it's Guido *wink*.) Consensus doesn't require every single person 
to agree.


-- 
Steven




More information about the Python-ideas mailing list