SyntaxError
SyntaxError: invalid syntax (in match/case block)
Traceback
Traceback (most recent call last):
File "main.py", line 4, in <module>
exit()
SyntaxError: invalid syntax (in match/case block)What causes this error
The match/case syntax was used incorrectly. This includes running on Python < 3.10, incorrect pattern syntax, or confusing capture patterns with constant patterns.
How to fix it
Ensure Python 3.10+ is installed. Use dotted names for constant comparison in patterns (e.g., `case Status.ACTIVE:`). Add colons after case lines. Use the wildcard `_` for default cases.
Code that causes this error
# Python < 3.10
match command:
case "quit":
exit()Fixed code
# Requires Python 3.10+
import sys
if sys.version_info >= (3, 10):
# match/case works here
pass
else:
# use if/elif chain on older Python
if command == "quit":
exit()About SyntaxError
This SyntaxError occurs when the match/case structural pattern matching syntax (introduced in Python 3.10) is used incorrectly. Common errors include using match/case on Python versions before 3.10, incorrect pattern syntax (like using assignment instead of capture patterns), forgetting the colon after case patterns, and using invalid guard expressions. The match statement is powerful but has specific syntax rules that differ from switch statements in other languages.
Patterns can be literals, capture patterns, sequence patterns, mapping patterns, class patterns, and OR patterns combined with `|`. A particularly confusing aspect is that bare names in patterns are capture patterns (they assign a value) rather than value comparisons — to compare against a named constant, use dotted names (like `Color.RED`) or guard clauses.
Common scenarios
Writing code with missing colons, parentheses, or brackets
Mixing Python 2 and Python 3 syntax when upgrading a codebase
Copy-pasting code from the web with formatting issues or invisible characters
Using reserved keywords as variable or function names