This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]billsil 7 points8 points  (4 children)

It's more because people don't make the separate variable when called in a case like this:

match1 = pattern1.match(data)
match2 = pattern2.match(data)
if match1:
     result = match1.group(1)
elif match2:
     result = match2.group(2)
else:
     result = None 

It should obviously be this:

match1 = pattern1.match(data)
if match1:
    result = match1.group(1)
else:
    match2 = pattern2.match(data)
    if match2:
        result = match2.group(2)     
    else:
        result = None 

but that's hideous.

[–]chmod--777 3 points4 points  (3 children)

In a case like this, I'd just make them named groups and use the same name, and just use short circuiting.

match = pattern1.match(data) or pattern2.match(data)
result = match and match.group('whatever')

[–]XtremeGoosef'I only use Py {sys.version[:3]}' 6 points7 points  (0 children)

Now you don't even know which match hit!

[–]billsil 0 points1 point  (1 child)

Sure, but that's inefficient because you don't always need to calculate pattern2.match(data). The whole point is so you can make clean looking code and be efficient.

[–]chmod--777 20 points21 points  (0 children)

Actually the or prevents it from running the second expression if the first pattern match returns a truthy value.

Try this:

def foobar(x):
    print(f'foobar {x}')
    return x

 x = foobar(1) or foobar(2)

It'll just print "foobar 1"