3

I am writing a program and python and want to use the match-case statement allowed in python 3.10 to be able to switch on 'enum' values i.e:

match token.type:
  case TOK_INT: #0
    # do stuff
  case TOK_STRING: #1
    # do stuff
  etc...

however trying to do this causes python to throw a SyntaxError: name capture 'TOK_INT' makes remaining patterns unreachable error. I know I can fix it by manually typing the number associated with each 'enum' variable but I am wondering if there is a better way of going about this?

james ray
  • 97
  • 7
  • 3
    Your inappropriate tag `switch-statement` shows that you have not understood, that python's [structural pattern matching](https://www.python.org/dev/peps/pep-0636/) is [not a switch statement](https://www.youtube.com/watch?v=ASRqxDGutpA). – Richard Neumann Feb 17 '22 at 00:52
  • @RichardNeumann i am well aware, in my use case however that's all I'm really trying to do but thanks for the heads up anyways. – james ray Feb 17 '22 at 00:55
  • Your problem is still that you have not understood what structural pattern matching does. It maches structures. And a single name (aka variable) has the same structure as any other single name. So the first *structural* match shadows all subsequent *structural* matches. I.e. there is no value matching. Read the docs and / or watch the video. – Richard Neumann Feb 17 '22 at 01:01
  • @RichardNeumann once again, I am aware. the more proper thing here is to just use a if-else chain and be done with it. I ask this question because I am not making production level code and I want something that looks nice, not because I'm looking for the most proper / correct this to do. I only wanted something that can be used LIKE a switch, not a literally switch. – james ray Feb 17 '22 at 01:11

1 Answers1

3

This will work with any dotted name (like math.pi). However an unqualified name (i.e. a bare name with no dots) will be always interpreted as a capture pattern, so avoid that ambiguity by always using qualified constants in patterns.

you can refer here

jinger7281
  • 71
  • 2