[Python-ideas] Give regex operations more sugar

Steven D'Aprano steve at pearwood.info
Thu Jun 14 03:29:03 EDT 2018


On Thu, Jun 14, 2018 at 06:33:14PM +1200, Greg Ewing wrote:
> Steven D'Aprano wrote:
> >- should targets match longest first or shortest first? or a flag
> >  to choose which you want?
> >
> >- what if you have multiple targets and you need to give some longer
> >  ones priority, and some shorter ones?
> 
> I think the suggestion made earlier is reasonable: match
> them in the order they're given. Then the user gets
> complete control over the priorities.

"Explicit is better than implicit" -- the problem with having the order 
be meaningful is that it opens us up to silent errors when we neglect to 
consider the order.

replace((spam, eggs, cheese) ...) 

*seems* like it simply means "replace any of spam, eggs or cheese" and 
it is easy to forget that that the order of replacement is *sometimes* 
meaningful. But not always. So this is a bug magnet in waiting.

So I'd rather have to explicitly specify the order with a parameter 
rather than implicitly according to how I happen to have built the 
tuple.

# remove duplicates
targets = tuple(set(targets))
newstring = mystring.replace(targets, replacement)

That's buggy, but it doesn't look buggy, and you could test it until the 
cows come home and never notice the bug.



-- 
Steve


More information about the Python-ideas mailing list