[Python-ideas] Experiment: Adding "re" to string objects.

Nick Coghlan ncoghlan at gmail.com
Tue Jul 21 23:19:26 CEST 2009


Steven D'Aprano wrote:
> On Tue, 21 Jul 2009 07:47:05 am Sean Reifschneider wrote:
> 
>>    if s.re.match(r'whatever(.*)'):
>>       s.re.group(1)
> 
> To me, the above is far less attractive than the standard idiom. That's 
> an aesthetic judgement which you might disagree with, but I believe 
> there's a far more critical flaw in the above idiom: it operates by 
> side-effect in an unsafe way.
> 
> Consider:
> 
> s = "yabba dabba doo"
> if s.re.match(r'y.bba'):
>     function(s)
>     print s.re.group(0)
> 
> You might expect the above to print 'yabba', but consider:
> 
> def function(s):
>     if s.re.match(r'.*(dabba)'):
>         log(s)
> 
> And now the snippet above will mysteriously print "yabba dabba" instead.
> 
> It's (presumably) easy enough to work around this:
> 
> s = "yabba dabba doo"
> if s.re.match(r'y.bba'):
>     # Save a copy of the re.group in case it gets mutated
>     group = s.re.group(0)
>     print function(s)
>     print group

While I agree with this objection in the case of strings (which are long
embedded in developers minds as immutable, hence unable to be altered by
other functions or threads), it doesn't bother me for a new convenience
type which is known to be mutable (and hence subject to side effects as
in the example above).

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia
---------------------------------------------------------------



More information about the Python-ideas mailing list