1

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?

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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}")

3 Comments

Thanks! How does that differ from match n: 5: return 'five'? h is a subject, int may be its value, right?
Ah - I see: peps.python.org/pep-0634/#literal-patterns are limited to numbers, strings and booleans. No types are allowed. That's arbitrary.
Types aren't literals, they're variables whose values are type objects.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.