osdir.com


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[Tutor] beginning to code


Steve D'Aprano wrote:
> ROGER GRAYDON CHRISTMAN wrote:

[...]
    
> > And most definitely if x is assigned outside my control, I
> > would definitely want some way to test or verify x's type
> > before I start using it, lest my random number generator
> > with its (A + B * C) % D finds itself concatenating
> > strings and formatting data.
> 
> You don't have to protect yourself from the caller's
> stupidity. You should think of Python functions having
> something like "Design By Contract" semantics: if you pass
> something that the function is not equipped to handle, then
> the (informal) contract 

"Informal Contracts" are not worth the paper they are
printed on. Like laws with no teeth, people don't follow
them. And then we end up with doc-strings that don't get
used, and contracts that are never created, much less
respected!

> is broken and the function can do anything it likes.  Of
> course we would prefer that the function would (in order of
> highest to lowest preference):
>
> - raise a clear TypeError or ValueError stating the failure;
> 
> - raise some implementation-dependent exception inside the body of the function;
> 
> - return some obviously invalid result;
> 
> rather than return something which *looks* valid but is
> wrong, but don't feel that it is *necessarily* your
> responsibility to guard against the caller's stupidity.
> "We're all adults here" and if the caller chooses to shoot
> themselves in the foot by passing a bad argument, they'll
> get what's coming to them.

But how is the caller to know what is a "bad" argument and
what is a "good" argument unless there is an explicit
contract, or at least, an informative doc-string? You know
as well as i do that (1) doc-strings are an under-utilized
feature, and (2) when they are utilized, they often times
neglected and eventually become out-of-sync with the code.

> (Defensive programming is not only the receiving function's
> responsibility. The caller should program defensively to
> ensure they don't pass the wrong arguments too.)

Well, congrats, that has the worst advice i ever heard!
Obviously, only the author of said interface knows best how
to defend against bad input, which is best achieved by type
checking. Heck, even the best documentation in the Universe
can't defend against bad input, therefore, type checking is
the only practical defense. The worse thing a program can do
is continue to run (as though everything is normal) after
receiving bogus input. Such has been the impetus of the
Mandelbug, and in extreme cases, the dreaded Heisenbug!

> In fact, there's a fine line between guarding against bad
> input, and guarding against input which in fact is
> perfectly fine, but merely is something you didn't think
> of.

And why am i not surprised to discover that your software
design philosophy relies heavily on "happy accidents"?