Home > Back-end >  Python match syntax for evaluating typing objects
Python match syntax for evaluating typing objects

Time:12-13

I'm trying to use a match block to evaluate the types being returned from typing.get_type_hints. I want to use the type hinting to determine what code path to take in order to instantiate the appropriate value.

class Foo:
  x: int = 0
  y: float = 0.0
  z: str = ''

name = 'x'  # comes from an external source
value = '42'
type_hints = get_type_hints(Foo)
foo = Foo()

match type_hints[name]:
  case int:
    foo[name] = int(value)
  case float:
    foo[name] = int(value)
  case str:
    foo[name] = value
  # TODO: other complex type parsing (e.g., Enums)

This is the error I'm getting:

C:\dev\bdk-git\bdk\venv\Scripts\python.exe C:/dev/bdk-git/bdk/material/reader.py
  File "C:\dev\bdk-git\bdk\material\reader.py", line 22
    case int:
         ^^^
SyntaxError: name capture 'int' makes remaining patterns unreachable

What is the correct syntax to accomplish what I want to do?

CodePudding user response:

match/case is used for pattern matching, not for simple equality testing. A simple name like int is a pattern that matches anything, and sets int to the value.

You should use ordinary if conditions.

h = type_hints[name]
if h == int:
    foo[name] = int(value)
elif h == float:
    foo[name] = float(value)
elif h == str:
    foo[name] = value
else:
    print(f"Unknown type {h}")

CodePudding user response:

I'm not sure what you're trying to do with the type hints here, but to structurally match based on class you need to provide a variable to which the value will be assigned, e.g.

foo = some_func()

match foo:
    case int(value):
        print(f"{value} is an integer")
    case float(value):
        print(f"{value} is a float")

This checks whether foo's type is already an int or a float (or a subtype thereof) and binds it to value, so no need to do int(value) inside the match body.

  • Related