F-strings in match case

Allow f-strings to be evaluated in a match case setting

match Foo:
  case f"Greater than {Bar}":
    print("Foo > Bar")

This currently raises a SyntaxError: patterns may only match literals and attribute lookups

That looks more like a job for regular expressions, to me. F-strings aren’t really matching tools, they’re formatting tools.

Nice idea, but this would be very hard to do in the case that there are format specifiers.

You can accomplish something very similar with

match Foo:
    case b if b == f"Greater than {Bar}":
        print("Foo > Bar")

Which I’ll grant you is a little more verbose, but removes the need to evaluate cases as arbitrary expressions (and f-strings can contain arbitrary expressions).

2 Likes