[Zope3-dev] Services in boolean context

Steve Alexander steve@cat-box.net
Sat, 07 Dec 2002 19:37:00 +0000


Marius Gedminas wrote:
> Yesterday we noticed a curious phenomenon: a placeful service was
> created and configured correctly, yet getService('...') could not find
> it.  The cause turned out to be an if statement like this in getService:
> 
>   if service:
>       ...
> 
> Our service inherited from a BTreeFolder, which has a __len__ method.
> When the folder is empty, __len__ returns 0, and that if statement
> fails.
> 
> Should getService be fixed to use 'if service is not None:'?

Yes. Guido was discussing exactly this kind of thing one evening during 
the Sprintathon.

If None is used as a marker for "no argument provided" as a method 
argument, then the comparison should explicitly be to None.


> I think
> not; the short form is so much more intuitive that someone is bound to
> use it after calling, say, queryService() somewhere.
> 
> I think the convention should be 'services ought to evaluate to True in
> boolean context', e.g. by defining __nonzero__ when they have a __len__.

No. That's unnecessary complexity, fixing what is really a problem of 
sloppy programming style.


> At the moment there are at least two services that inherit from
> BTreeFolder -- CachingService and ConnectionService.  AFAIU the plan is
> to change their architecture so that they are no longer folders, and
> this question will no longer be relevant to them.
> 
> There's a related question -- should empty folders evaluate to False?

That's not relevant, given my answers above.

> I haven't given it much thought yet.  Empty containers are False,
> though, so it makes sense at a glance.

If you want to treat a folder as having the __len__ and __getitem__ 
protocols, then yes, when empty it should be false.

--
Steve Alexander