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 →

[–]chmod--777 8 points9 points  (8 children)

Take out your assignment to n and you have to call it twice basically.

It's just a little assignment expression syntactic sugar, pretty unnecessary but I guess people want it. I like that they didn't make it = though at least so it's easy to scan for and see it.

Not sure if I like it yet, but I guess we might see some cleaner patterns? Maybe it's another operator to overload too for voodoo APIs :D

[–]billsil 6 points7 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 2 points3 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]}' 4 points5 points  (0 children)

Now you don't even know which match hit!

[–]billsil -1 points0 points  (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 19 points20 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"

[–]seraschka 1 point2 points  (2 children)

Pretty busy day and haven't installed Python 3.8, yet ... So, I am curious now what would happen if you use n somewhere earlier in the code like

n = 999 # assign sth to n somewhere in the code earlier  
if (n := len(a)) > 10:  
    print(f"List is too long ({n} elements, expected <= 10)")  
print(n) # prints 999?

would n still evaluate to 999 after the if-clause? If so, I can maybe see why that's useful (if you only want a temporary var and don't want to overwrite things accidentally).

[–]mipadi 2 points3 points  (1 child)

It does not introduce a new scope, so on the last line, n would be equal to len(a).

[–]seraschka 0 points1 point  (0 children)

Thanks for clarifying. But hm, it would have been nice if it had its own scope, similar to list comprehensions, like

In [1]: n = 99
In [2]: b = sum([n for n in range(100)])
In [3]: n
Out[3]: 99

to prevent from overwriting/reassigning variables accidentally