Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unable to subtract in case pattern?

I’m trying to use Python 3.10 structural pattern matching in Python shell:

match a:
   case (2 - 1):

after entering the second line, it gives me the following error:

  File "<stdin>", line 2
    case (2 - 1):
              ^
SyntaxError: imaginary number required in complex literal

NOTE: I know there’s no code to execute after the case, I’m doing this in the shell and it throws this error immediately.
ALSO, I’m aware that I can store them as per this answer, but I’d rather do this directly if there is a way.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You’re not allowed to compute arbitrary expressions in a pattern. There’s just too much room for conflict with other pattern syntax.

For example, there’s little point doing 2 - 1 as a pattern. If you had a value stored in a variable x, you might want to match against x - 1:

case x - 1:
    ...

but consider what case x means:

case x:
    ...

case x means "match anything and set x equal to the thing matched". It would be extremely confusing for case x and case x - 1 to do such extremely different things.

The error message you got is because there’s one special case where addition and subtraction are allowed in a pattern, as part of a complex number "literal":

case 1+2j:
    ...

An expression like 1+2j or 1-2j is syntactically an addition or subtraction expression, not a single literal, so Python has to allow this specific case of addition or subtraction to allow constant patterns with complex constants. The error message comes from Python expecting the - to be part of a complex constant.

If you want to match against a computed value, use a guard:

case x if x == arbitrary_expression:
    ...
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading