Returning none

C.Laurence Gonsalves clgonsal at keeshah.penguinpowered.com
Fri Sep 3 18:24:51 EDT 1999


On Fri,  3 Sep 1999 13:01:38 -0500 (CDT), Skip Montanaro <skip at mojam.com> wrote:
> C> This is akin to saying array-bounds checking should be done by PyLint
> C> rather than the runtime. The problem is, a lot of these checks simply
> C> can't be done statically.
> 
> I'll assert here without proof that the primary mistake programmers are
> likely to make in this regard is to include both "return <some value>" and
> "return" (or the terminating byte code) in the same function.  This sort of
> error a program like PyLint could indeed check.  There's be no need to add
> the overhead of checking for incorrect function/procedure return semantics
> at run-time.

There's the example I posted, which was something like:

    def seqToString( seq ):
        result = '['
        if len(seq)>0:
            result = '[' + ' ' + repr(seq[0])
            for i in seq[1:]:
                result = result + ', ' + repr(i) 
        result = result + ']'

PyLint can't catch it, because there's nothing actually wrong with this
function. When I call it like this though:

    a = seqToString( b )

then I've done something wrong. Only runtime checks could catch that.

> C> In fact, while I was originally proposing some compile-time checks as
> C> well, I've basically given up on those. They were mostly incomplete
> C> (Python is too dynamic to be able to do much static checking in this
> C> situation) and Tim found a real problem with them.
> 
> Perhaps I missed something (this thread is getting rather long and drawn
> out).  What sort of situation would PyLint miss that my proposed static
> check wouldn't catch?

Tim brought up the idea of having a function that always raises an
exception:

    def calcStuff(x):
        if isGood(x):
            return x*42;
        else:
            kablowie( "x is bad!" )

    def kablowie(s):
        raise "Argh: " + s

The static checks would incorrectly think calcStuff was inconsistent.
You can't trace into kablowie from calcStuff, because there's no telling
what the value really is at runtime when I call calcStuff.

When all else is equal, I prefer compile-time checks. This isn't a
situation where they can be very useful though. Even if the language
were changed to allow tagging of functions as "has result" or "doesn't
have result", the "kablowie" problem still exists...

Returning "nothing", and checking if it is returned into an expression,
seems like the only viable way to check for this type of error. It's
also consistent with the fact that maps and sequences all raise
exceptions when you try to access a nonexistant value. (ie: KeyError or
IndexError)

-- 
  C. Laurence Gonsalves            "Any sufficiently advanced
  clgonsal at kami.com                 technology is indistinguishable
  http://www.cryogen.com/clgonsal/  from magic." -- Arthur C. Clarke




More information about the Python-list mailing list