Home > database >  Python match-case statement with types throwing errors
Python match-case statement with types throwing errors

Time:03-24

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

CodePudding user response:

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

CodePudding user response:

Match won't work in the way you're trying to use it. You can work around it though:

lst = [1, 2]

variable_type = type(lst)

match (variable_type,):
 case (list,):
   print("It's a list")
 case _:
   print("It's something else")
  • Related