Terry Carroll wrote:

> 1A) a variation of option 1 (which is why I said "depending on how you
> count" above):  duck-typing with error recovery.
> 
> def incr(n):
>   "returns an incremented value of n, or None if n is not incrementable"
>   try:
>     return n + 1
>   except:
>     return None
> 
> This will try to return a value equal to N + 1, but if n does not quack 
> like a duck, it just returns None (and it's up to the caller to deal with 
> it).

This is generally a bad idea. The problem is that you depend on the 
caller checking the return value for None. If it doesn't, it will 
probably get some other exception later which will be hard to track down 
because the source will not be clear. Depending on the caller to check 
for errors is unreliable. Raising an exception forces the issue - the 
caller has to catch the exception or propagate it, it can't just ignore it.

IIRC exceptions were introduced in C++ to give an alternative to 
checking for errors.

On the other hand, if the caller *does* check for errors, the code can 
quickly get very cluttered with error checking. Long ago and far away I 
wrote a lot of MacOS code. At that time, almost every system call 
returned an error code that had to be checked. Functions tended to look like
err = DoSomethingWithX(x);
if (err != noErr)
   return err;

err = DoSomethingElse(y);
if (err != noErr)
   return err;

etc. With exceptions this can be written much more simply, compactly and 
readably as
DoSomethingWithX(x);
DoSomethingElse(y);

> In a program I'm writing now, I would like to use duck-typing, but I don't
> think it works well.  In my particular case, to simplify it a bit, I'm
> writing a method that can either take a string that contains SQL
> statements; or a list or tuple that contains strings of SQL statements.  
> Duck-typing doesn't work too well here, because a string of characters
> looks an awful lot like a list or tuple of one-character strings for most
> duck-typing tests.  I'd have to put together a weird duck-typing approach 
> that would ultimately be a type-checking approach disguised as 
> duck-typing; so I opted to just be up-front about it and check the type 
> (using isinstance, of course).

This is one of the common cases where there is no simple alternative to 
LBYL - a function that can take a string or a list of strings as a 
parameter.

Kent
_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to