On Tue, Dec 3, 2019, at 20:46, Oscar Benjamin wrote:
> What exactly is the idiom here?
> 
> Using bare next is not a good idea because it leaks StopIteration
> which can have awkward side effects. So are you suggesting something
> like
> 
> result = next(re.finditer(...), None)
> if result is None:
>     # raise or something
> else:
>     # use result
> 
> I would be in favour of adding an alternative to next that raises a
> different exception when the result isn't found.

result, *_ = re.finditer() raises ValueError.

Perhaps a way to prevent the values from being consumed and a list constructed 
would be useful - maybe add a "result, * =" syntax?

C# has First, Single, FirstOrDefault, and SingleOrDefault methods [the 
OrDefault versions return null/zero instead of raising an exception, and single 
raises if there are multiple items]

These can be envisioned roughly as

def first(it):
    x, *_ = it
    return x

def first_or_default(it):
    x, *_ = [*it] or [None]
    return x

def single(it):
    x, = it
    return x

def single_or_default(it):
    x, = [*it] or [None]
    return x
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/ZMNBNOIBV6YA3H6TA2V4TQC3TJ65XTDQ/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to