1

I have a simple function that should output a prefix based on a pattern or None if it does not match. Trying to do a walrus it does not seem to work. Any idea?

import re

def get_prefix(name):
    if m := re.match(f'^.+(\d\d)-(\d\d)-(\d\d\d\d)$', name) is not None:
        return m.group(3) + m.group(2) + m.group(1)

get_prefix('abc 10-12-2020')

Traceback

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in get_prefix
AttributeError: 'bool' object has no attribute 'group'
khelwood
  • 46,621
  • 12
  • 59
  • 83
Bruno Vermeulen
  • 1,862
  • 2
  • 9
  • 18
  • 4
    You're setting `m` to `re.match(f'^.+(\d\d)-(\d\d)-(\d\d\d\d)$', name) is not None`, which is a boolean. Get rid of `is not None`. – khelwood May 12 '21 at 10:36
  • 3
    `is not None` is redundant anyway, because `re.match` always returns either a (non-falsy) match object or `None`. – bereal May 12 '21 at 10:38
  • @bereal It's theoretically faster to check `is None` since it compares the identities directly instead of having to call `__bool__()`. Also it's more explicit and, according to PEP-8, more Pythonic. – Markus Meskanen May 12 '21 at 10:39
  • 1
    @MarkusMeskanen PEP-8 refers to the cases when an accepted value can be Falsy. Which is not the case. – bereal May 12 '21 at 10:41

1 Answers1

3

You're setting m to re.match(f'^.+(\d\d)-(\d\d)-(\d\d\d\d)$', name) is not None, which is a boolean.

You probably mean

if (m := re.match(f'^.+(\d\d)-(\d\d)-(\d\d\d\d)$', name)) is not None:

But you don't need is not None here anyway. Matches are truthy and None is falsey. So you just need:

if m := re.match(f'^.+(\d\d)-(\d\d)-(\d\d\d\d)$', name):

(Arguably it's better practice to use () whenever you're using an assignment expression, to make clear what's being assigned.)

See PEP572#Relative precedence of :=

khelwood
  • 46,621
  • 12
  • 59
  • 83