On Dec 3, 2019, at 17:47, Oscar Benjamin <oscar.j.benjamin@gmail.com> wrote:
On Tue, 3 Dec 2019 at 12:48, Paul Moore <p.f.moore@gmail.com> wrote:
My impression is that he was asking for a re.findfirst(...) function to give a more discoverable name to the next(re.finditer((...)) idiom.
As a single example of defining a dedicated function to replace a one-liner, I think it's marginal at best (although discoverability *is* important here). But IMO it is true that using next(some_iterator) to mean "get the first value returned" is something that's needed relatively frequently, but often overlooked by people. I'm not sure there's a good solution, though - adding an alias first() for "next() when used to get the first element" is probably overkill, and apart from dedicated syntax, it would be hard to find something much shorter than next().
Maybe it's just an education issue, people aren't sufficiently familiar with the idiom?
What exactly is the idiom here?
The OP’s proposal was for a findfirst function that takes a mandatory default value. So presumably the idiom is just next with a default value: def findfirst(pattern, text, default): return next(finditer(pattern, text), default) And this “first or default” thing is pretty common, not just restricted to the OP’s use case, and next already handles it perfectly, but apparently not enough people know about it.
Using bare next is not a good idea because it leaks StopIteration which can have awkward side effects.
Not the two-argument form.
So are you suggesting something like
result = next(re.finditer(...), None) if result is None: # raise or something else: # use result
Using None as a sentinel would work here, but as a generic idiom it’s not a good habit, because plenty of other functions can validly iterate None.
I would be in favour of adding an alternative to next that raises a different exception when the result isn't found.
If you need that, it’s pretty trivial to write yourself. If you think other people need it and don’t know how to write it, why not submit it to more-itertools and/or tools? If it gets enough uptake, you can always suggest adding it to itertools, or even modifying next to take a keyword argument or something.