2
variable_type = type(variable)
match variable_type:     

  case list:      
       pass

  case int: 
       pass

Been trying implement a match-case statement similar to the one above.

case list: -> Irrefutable pattern is allowed only for the last case

case int: -> "int" is not accessed

My current workaround has been using if-elif statements such as below, but I'm confused why the match-case statement is invalid but the if-elif works.

variable_type = type(variable) 
if variable_type == list:     
    pass

elif variable_type == int:     
     pass
yunji
  • 29
  • 3
  • Welcome to SO. You could always use ```isinstance(variable, int)``` to test for integers.. or in the place of ```int```, you could use ```list``` or ```dict```. – ewokx Mar 24 '22 at 06:31
  • I've been mainly using the match-case statements to test the class types that I've defined in the program. Guessing those will work in place as well. Thank you for providing an alternative solution, but I'm still curious why the match-case isn't valid haha. – yunji Mar 24 '22 at 06:33
  • Flexible typing and type interfaces is a major advantage of writing in python. See duck typing. Not sure your goals, but a common pattern in python is to try and treat the variable as a list, int, etc., then catch the exception if it fails and proceed to the next case. – Xingzhou Liu Mar 24 '22 at 07:29

2 Answers2

-1

You're getting errors about "irrefutable patterns" because that's what python calls case blocks that never fail to match.

case list: always matches because it's not treating list like a type. Whatever the data is, it'll be put in a new variable called list

To see why irrefutable case blocks have to go at the end, consider:

x = "foo"
match x:
    case val:
        print("got: ", val)  # this would always run
    case val2:
        print("got: ", val2)  # this would never run

I think the best you're going to be able to do is turn everything into strings:

x = [1, 2]
variable_type = str(type(x))
match variable_type:

    case "list":
        pass

    case "int":
        pass

    case something_else:
        raise ValueError(f"got {something_else}")

MatrixManAtYrService
  • 8,023
  • 1
  • 50
  • 61
-2

As far as I can tell you are using match-case correctly. Are you using the correct version of python?

Match-Case is only available in python 3.10+

SPYBUG96
  • 1,089
  • 5
  • 20
  • 38
  • I'm using match-case statements in the same program, but with the cases being specific strings. Only giving me that issue when I use types inside the case. – yunji Mar 25 '22 at 03:21