- SyntaxError: invalid syntax when using match case
- 1 Answer 1
- Python match case invalid syntax
- # SyntaxError: invalid syntax when using Match case in Python
- # Checking your version of Python
- # Implementing your own Match-case statement
- # Having a syntactical error right before the Match-Case statement
- # Conclusion
- Solution for the “SyntaxError: invalid syntax when using Match case” in Python
- Why does this error occur?
- Solution for the “SyntaxError: invalid syntax when using Match case” error in Python
- Summary
- match case in micropython — SyntaxError: invalid syntax
- 1 Answer 1
- Match case invalid syntax, but no syntax error without match code
- 2 Answers 2
SyntaxError: invalid syntax when using match case
I’ve been trying to use a match case instead of a million IF statements, but anything I try returns the error:
match http_code: ^ SyntaxError: invalid syntax
http_code = "418" match http_code: case "200": print("OK") case "404": print("Not Found") case "418": print("I'm a teapot") case _: print("Code not found")
I’m aware that match cases are quite new to python, but I’m using 3.10 so I’m not sure why they always return this error.
@Jiwon What do you mean deprecated? This feature was only introduced in Python 3.10 so of course you’ll get an error with 3.9.
1 Answer 1
The match / case syntax, otherwise known as Structural Pattern Matching, was only introduced in Python version 3.10. Note well that, following standard conventions, the number after the . is not a decimal, but a separate «part» of the version number. Python 3.9 (along with 3.8, 3.7 etc.) comes before Python 3.10, and does not support the syntax. Python 3.11 (and onward) do support the syntax.
While it’s possible that a syntax error on an earlier line wouldn’t be noticed until the match keyword, this sort of syntax error is much more a sign that the Python version isn’t at least 3.10 .
This code will fail with an assertion if the Python version is too low to support match / case :
import sys assert sys.version_info >= (3, 10)
Or check the version at the command line, by passing -V or —version to Python. For example, on a system where python refers to a 3.8 installation (where it won’t work):
$ python --version Python 3.8.10 $ python Python 3.8.10 (default, Nov 14 2022, 12:59:47) [GCC 9.4.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>>
If you’re trying to use a virtual environment, make sure that it’s activated (Linux/Mac howto, Windows (CMD) howto, Windows (Powershell) howto, using PyCharm).
Python 3.10.0 (tags/v3.10.0:b494f59, Oct 4 2021, 19:00:18) [MSC v.1929 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license()" for more information. >>> http_code = "418" >>> match http_code: . case "200": . print("OK") . case "404": . print("Not Found") . case "418": . print("I'm a teapot") . case _: . print("Code not found") Out[1]: "I'm a teapot"
Python match case invalid syntax
Last updated: Feb 23, 2023
Reading time · 3 min
# SyntaxError: invalid syntax when using Match case in Python
The «SyntaxError: invalid syntax when using Match case» error is most often caused when:
- Using a Python version that is older than 3.10.
- Having a syntactical error before the Match-Case statement.
- Having a syntactical error in the Match-Case statement.
Copied!File "/home/borislav/Desktop/bobbyhadz_python/main.py", line 2 match status: ^ SyntaxError: invalid syntax
The syntax for Structural Pattern Matching is the following.
Copied!match subject: case pattern_1>: action_1> case pattern_2>: action_2> case pattern_3>: action_3> case _: action_wildcard>
Here is an example that prints a string that corresponds to the provided status code.
Copied!def http_error(status): match status: case 200: return "OK" case 400: return "Bad request" case 404: return "Page not found" case 500: return "Internal Server error" case _: return "Something went wrong" print(http_error(400)) # 👉️ Bad request
However, if I run the exact same code sample using a Python version older than 3.10, I’d get the error.
Notice that I ran the code with Python 3.9, which caused the SyntaxError because Structural Pattern Matching has been added in Python 3.10.
# Checking your version of Python
You can use the python —version command to check your version of Python.
Copied!python --version python3 --version
Alternatively, you can access the version attribute on the sys module.
Copied!import sys print(sys.version)
Run your code with python module_name.py to get your Python version.
If you have an older Python version than 3.10, download the latest version from the official python.org website.
# Implementing your own Match-case statement
If you aren’t able to switch to a version of Python that is greater than or equal to Python 3.10, you can implement your own Match-Case statement.
Copied!def http_error(status): status_dict = 200: 'OK', 400: 'Bad request', 404: 'Not Found', 500: 'Internal Server error', > default_status = 'Something went wrong' return status_dict.get(status, default_status) print(http_error(200)) # 👉️ OK print(http_error(400)) # 👉️ Bad request print(http_error(10000)) # 👉️ Something went wrong
We stored the possible values in a dictionary and use the dict.get() method to return the corresponding value.
If the supplied status is not one of the possible values, we return a default value.
The dict.get method returns the value for the given key if the key is in the dictionary, otherwise a default value is returned.
The method takes the following 2 parameters:
Name | Description |
---|---|
key | The key for which to return the value |
default | The default value to be returned if the provided key is not present in the dictionary (optional) |
If a value for the default parameter is not provided, it defaults to None , so the get() method never raises a KeyError .
# Having a syntactical error right before the Match-Case statement
Another common cause of the error is having a syntactical error right before the Match-Case statement.
Make sure all the parentheses, curly braces, square brackets, single and double quotes match and have been closed.
You can comment out the Match-Case statement and run your code to verify if it is the cause of the error.
The syntax for Structural Pattern Matching is the following.
Copied!match subject: case pattern_1>: action_1> case pattern_2>: action_2> case pattern_3>: action_3> case _: action_wildcard>
The match statement takes a value and compares it to the patterns in the case blocks.
If an exact match is not found, the last case, a wildcard _ (if provided) is used as the matching case.
Copied!def http_error(status): match status: case 200: return "OK" case 400: return "Bad request" case 404: return "Page not found" case 500: return "Internal Server error" case _: return "Something went wrong" print(http_error(200)) # 👉️ OK print(http_error(400)) # 👉️ Bad request print(http_error(10000)) # 👉️ Something went wrong
# Conclusion
To solve the «SyntaxError: invalid syntax when using Match case» error, make sure:
- You’re using a Python version that is greater than or equal to 3.10.
- You don’t have any syntactical errors before the Match-Case statement.
- You don’t have any syntactical errors in the Match-Case statement.
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
Solution for the “SyntaxError: invalid syntax when using Match case” in Python
Error “SyntaxError: invalid syntax when using Match case” in Python arises when you use the wrong syntax of conditional structure match-case or because your Python version is older than ‘3.10’. Make sure to use the correct syntax of conditional structure match-case or upgrade the version of Python to solve this error. Keep reading for detailed information.
Why does this error occur?
Here are some of the main reasons why you get the error message: “SyntaxError: invalid syntax when using Match case”
- Using a Python version older than ‘3.10’.
- Using the wrong syntax of the match-case statement
Solution for the “SyntaxError: invalid syntax when using Match case” error in Python
If you are familiar with the switch-case statement in the C programming language, Python implements a similar method called a match-case statement.
The program will compare the object’s value with each case’s value. If it finds a match, it will perform the corresponding action and terminate the match-case block. In case all values do not match, the program will execute the commands inside the last case statement.
match object: case : case : case : case _:
- object: an object used for evaluation
- value_#: possible values used to compare with ‘object’
- code_snippet_#: code that performs actions corresponding to each specific case
Here is an example of how we implement this method:
# Implement a match-case statement def engToFrench(content): match content: case 'Hello': return "Bonjour" case 'Goodbye': return "Au revoir" case 'Good luck': return "Bonne chance" case 'Thank you': return "Merci" case _: return "No word found" result = engToFrench('Thank you') print(result)
Make sure to follow the correct syntax of the match-case statement as we provide above to avoid getting the error message: “SyntaxError: invalid syntax when using Match case”.
A match-case statement is a new construct in Python 3.10 (all older versions are not supported). Therefore, an error will occur if you use the match-case statement in Python with a version older than ‘3.10’.
You can check the version of Python you are using with the following command:
Suppose you get a version older than ‘3.10’ like in this example(3.9.12). Please update Python to the latest version.
Summary
In conclusion, we have shown you how to fix the “SyntaxError: invalid syntax when using Match case” in Python. Make sure to use the correct syntax of conditional structure match-case or upgrade the version of Python to solve this error. Hopefully, the information we provide in this post will be helpful to you.
match case in micropython — SyntaxError: invalid syntax
I am using python 3.10.5 on my raspberry pi pico and I am trying to use match & case instead of if statements When I try to run the program it returns an error:
Traceback (most recent call last): File "", line 22 SyntaxError: invalid syntax
async def BlueTooth(delay): while True: if uart.any(): command = uart.readline() #print(command) # uncomment this line to see the received data match command: case b'1': led.value(1) case b'0': led.value(0) write_i2c("cmd: <>\n<>".format(command, Commands.get_command_action(str(command)))) await asyncio.sleep(delay)
I have checked, and everything should be normal, what can cause the problem?
BTW, I am using Thonny as my editor.
The line beginning with write_i2c needs to be indented to put it inside the second case , or dedented to take it out of match .
1 Answer 1
MicroPython implements the entire Python 3.4 syntax (including exceptions, with , yield from , etc., and additionally async / await keywords from Python 3.5 and some select features from later versions).
match / case are new as of Python 3.10, six releases after the last version of the Python language spec MicroPython claims full support for. And it’s a ridiculously complex addition to the language (relying on a complete replacement of the simpler LL(1) parser with a more flexible/powerful/complex PEG parser among other things). They don’t support it yet, but it’s on their todo list. When it’s supported, the «MicroPython differences from CPython » Python 3.10» docs should be updated to indicate that support is completed.
Match case invalid syntax, but no syntax error without match code
I’m running python 3.9.7 and am making a youtube video info viewer / downloader. Without the match statement the code runs fine and doesn’t have any errors with concern to missing brackets. An interesting thing is that Atom doesn’t show match with any colour in my code, however it seems not to do that in a blank file with only the match anyway.
# A youtube info and downloader import getpass from pytube import YouTube from pathlib import Path username = getpass.getuser() downloads_path = str(Path.home() / "Downloads") # Create video object link = input("Enter video link (Don't forget https://): ") video_object = YouTube(link) # Print info print(f"Title: ") print(f"Length: minutes") print(f"Views: million") print(f"Author: ") # Download print("Download: (b)est | (w)orst | (a)udio | (e)xit") download_choice = input(f" $ ") match download_choice: case: "b": video_object.streams.get_highest_resolution().download(downloads_path) case: "w": video_object.streams.get_worst_resolution().download(downloads_path) case: "a": video_object.streams.get_audio_only().download(downloads_path)
2 Answers 2
I had to install Python 3.10 from python.org because matching was only added in Python 3.10.
When getting invalid syntax error on match statement, check that you have at least python 3.10 installed as this is the version it was released.
You can check your current version
import sys print(sys.version)
Install the latest version of python (Windows)
Download installer: https://www.python.org/downloads/
Chocolatey update
cmd install chocolatey if not already (paste to admin shell)
@"%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe" -NoProfile -InputFormat None -ExecutionPolicy Bypass -Command "[System.Net.ServicePointManager]::SecurityProtocol = 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://community.chocolatey.org/install.ps1'))" && SET "PATH=%PATH%;%ALLUSERSPROFILE%\chocolatey\bin"
choco upgrade python3 --pre