[Python-ideas] sentinel_exception argument to `iter`

Steven D'Aprano steve at pearwood.info
Sat Feb 8 01:30:12 CET 2014


On Fri, Feb 07, 2014 at 04:54:04PM -0500, Terry Reedy wrote:
> On 2/7/2014 3:39 AM, Steven D'Aprano wrote:
> 
> >is simpler than the proposed behaviour:
> >
> >   "the callable is called until it returns the sentinel, unless the
> >    sentinel is an exception instance or class, in which case the
> >    callable is called until it raises that exception, or one which is
> >    compatible with it"
> 
> To repeat, for the 3rd or 4th time, this is not the behavior that either 
> I or Ram proposed. I even provided code to be clear as to what I mean at 
> the time.

You did write:

    No new parameter is needed. We only need to add 'or raises' to the 
    two-parameter iter definition "In the second form, the callable is 
    called until it returns the sentinel." to get "In the second form, 
    the callable is called until it returns or raises the sentinel."


I agree that what I described is not what Ram suggested, but I believe 
that it was you who first suggested overloading the meaning of the 
sentinel argument depending on whether it was an exception or not. If 
you've changed your mind, I'll be glad to hear it, and you can stop 
reading here. If you haven't, then I admit I'm still confused, and would 
be grateful for a short, simple, obvious example of what you are 
proposing and how it differs from the current behaviour.

I must admit that I haven't studied your code snippets in detail, 
particularly since you descibed at least one of them as "twisted and 
awful". I don't believe that an iterable that returns exceptions (either 
exception classes, or exception instances) is either twisted or awful.

However, I do believe that overloading the sentinel argument depending 
on the specific type of value provided *is* twisted and awful. That sort 
of behaviour should only be allowed when there is otherwise no possible 
reason for the function to return that kind of value. E.g. contrast 
iter() with (say) str.replace. The optional count argument, if given, 
must be an int. There is no valid reason for supplying (say) count='a 
string'. So we might, hypothetically, overload the count operator to say 
"if count is a string, then do this special behaviour instead". Even 
that is dubious, but at least it is backwards-compatible.

With iter(), on the other hand, the callable can return values of any 
type, it is completely general. Likewise the sentinel can be of any 
type. We wouldn't even dream of overloading the behaviour of iter when 
sentinel happens to be a string. We shouldn't do so if it happens to be 
<insert any type here>, no matter how unusual the type.


-- 
Steven


More information about the Python-ideas mailing list