PyCharm 2022.2 Help

Pattern matching

PyCharm provides support for pattern matching introduced in PEP-634, PEP-635, and PEP-636 and available since Python 3.10.

Pattern matching has been added in the form of a match statement and case statements of patterns with associated actions:

match subject: case <pattern_1>: <action_1> case <pattern_2>: <action_2> case <pattern_3>: <action_3> case _: <action_wildcard>

Patterns consist of sequences, mappings, primitive data types, and class instances. Pattern matching allows extracting information from complex data types, branch on the structure of data, and apply specific actions based on different forms of data. For more information about examples and use cases, see the feature overview at docs.python.org and PEP-636 (tutorial).

PyCharm provide the following coding assistance for pattern matching:

Syntax highlighting

PyCharm supports parsing and highlighting of the matching syntax.

Pattern matching: literals

To alter the default code styles, press Ctrl+Alt+S to open the IDE settings and select Editor | Code Style | Python. See more details in Configuring code style.

Keyword completion

Start typing one of the pattern matching specific keywords, such as match or case, and PyCharm will show you a completion list for quick editing:

Keyword completion

See Code completion for more details about code completion in PyCharm.

Code inspections

With code inspections available in PyCharm, you can detect problematic parts of code in pattern matching constructs.

Unreachable code

The IDE shows a warning when a code element cannot be reached through the execution. In matching constructs this warning is shown because there should be only one universally matching pattern. All the following patterns are considered unreachable.

Unreachable code in pattern matching

Redeclared variable

When you declare a variable name that is used in pattern matching, PyCharm highlights it and shows a warning. This happens because variable names are assignments, and their previous values are not taken into account.

Redeclared variable in pattern matching

To configure code inspections, press Ctrl+Alt+S to open the IDE settings and select Editor | Code Style | Python, then locate the inspection you want to edit, and apply the changes. See more details in Change inspection severity and Disabling and enabling inspections

Last modified: 26 August 2021