Relying on the behaviour of empty container in conditional statements

horizon5 matt.horizon5 at gmail.com
Tue Jul 11 17:15:18 EDT 2006


Interesting replies, thank you all.
Since the language defines the bahviour, I'm all for  using it (when
appropriate).

> there is no distinction between seq is None on the one hand and seq
> being a valid empty sequence on the other hand.
>
> I feel that that is an import distinction, and it's the reason I find
> myself using len() from time to time (even though I can't think of a use
> case right now).

Depends on the context.

def action1(container):
    if container:
        do_something()
    else:
        do_somthing_else()

def action2(mutator):
    container = list()
    mutator(container)
    if container:
        do_something()
    else:
        do_somthing_else()

def action3(container):
     n = len(container)
     if n > 0:
         report("%i items left in container" % n)
     else:
         alert("container is empty")

In these examples;
action1 receives the container, so we *might* have received a None,
thus we would not get an error that we might expect.  The meaning is
lost, so action1 could say:

if container is not None and container:

Or it could be bad design, and one compose do_somthing and
do_something_else to take the container reference and dispatch
accordingly. (these arn't concrete examples so will depend on context).

in action2 however, the function is repsonsible for creating the
container, and thus (with good unit tests as always) we should be able
to assume that mutator does not destroy the reference to container, and
the if is fine.

In action3, we have a use for the lenth of container, so we might as
well use it.

So, imho, there's no problem with using the behaviour of the language,
where appropriate.
As another contributer(s) have mentioned, using the defined behaviour
(as oppsed to invoking len)
can eliviate the need to make as many changes.
The problem for me is: how to communicate the benefits of adhereing to
a language, rather than fighting against it, either because it doesn't
feel right or is not explicit enough for people who may not be aware of
the language's bahviour.  Of course over time, we read docs, and come
to learn to love the things a language gives us (esp. in Python;).

I don't think changing jobs is the answer; who says in the next job I
may have that they won't hire new people who aren't vetern Pythonistas?
 I'm sure the long term solution lies in eductation, but I'm not sure
what the short term solution is.

And don't I sound arrogant? Programmers feel threatended by someone who
has more experience, and feel inadequete (i did at least).  So, perhaps
I should read up on some communication case studies.  Can anyone point
me to such resources?

Thanks




More information about the Python-list mailing list