Pattern Matching Statements in Python: What's the Fuss All About?

DZone 's Guide to

Pattern Matching Statements in Python: What's the Fuss All About?

Pattern Matching Statements in Python — writing easier scripts using python and handle data without having to worry.

· DevOps Zone ·
Free Resource

Python is one of the most popular programming languages on the planet right now. Gone are the days when Java used to come up in conversations as a solution for every software development issue. Today, even though Java and other languages are being used extensively in industries it is Python that has taken the command of all.

Be it the field of research and development to enterprise mobility solutions. Python is finding its way to the top of every field. In one of the instances, the cloud storage giant Dropbox developed a Python code for their application that was more than two thousand lines of length.

The Fuss About Python

Not only this but with the growing popularity of Python and its large open community contributions, developers are becoming more and more drawn towards using the language. This provides an opportunity for small enterprises to leverage Python’s latest features that are input from the open community. Similarly, it also provides an opportunity to bug enterprises especially in the domain of research and development to look at Python’s features and add value to them with new modules and frameworks. One of the biggest examples of this is Facebook’s PyTorch framework. It gives people working in the domain of machine learning and deep learning to design models more conveniently and with the support of a robust framework.

The fuss about Python is not only due to its open-source contributions but due to many reasons.  First, Python can be used as a scripting language, making programming much convenient for desirable tasks. On the other hand, it is a dynamic language and offers a greater deal of flexibility when it comes to writing codes. Thus, developers find writing scripts in Python much easier than any other language.

Even though Python offers a lot of flexibility, sometimes that can be an issue. Especially when writing large programs, when multiple teams are working on it, heavy documentation is required and the code is always not very clear. This being the reason, Python is generally not used for writing long codes and pother alternatives are explored.

This and other factors in Python make development a little cumbersome, which is why Python developers often crib over the unclear syntax of the language. However, this calls for improvements and updates in Python, which is what the parent organization does. The Python Software Foundation manages the software and makes sure that the shortcomings of the language are addressed in subsequent updates.

One of the most talked-about updates of the programming language Python that is yet under construction but being considered seriously is that of pattern matching syntax. Regardless of whether you’re familiar with this statement before, we’ll help you understand it in a clear context.

Pattern Matching Syntax

In most languages, the string is passed and handled using regular expressions. This regular expression is used for matching patterns in a programming language. For example, in Python there is a ‘re’ module that provides support for the regular expressions. Implying from this, a search result is often written as:



Match = re.search(pattern, string)

The above statement takes an expression pattern and a string. It then looks up the pattern within that string. If the desirable pattern is identified or found within the string provided, the function returns a match object. In all other cases, it returns a ‘None’.

The problem is regular expressions are quite complicated mini-language. They heavily rely on special characters to match unknown string. However, when it comes to letters, numbers, and others, they always match with themselves.

Thanks to the Python software foundation that it is now considering a new proposal PEP 622 that will finally bring Python matching statements to the language for ease of use. This will not only provide for a cleaner syntax but also give developers in Python a structured way to handle data without having to worry about workarounds and alternative options.

In other programming languages such as C, pattern matching is a common feature that is provided for using the switch/case statements. This allows for a wide variety of actions to be taken place for a given variable.

Even though traditionally python lacks pattern matching syntax, it has been used to date using alternate methods such as if-else statements, elif, else, etc. However, PEP 622 proposes a better syntax of the form match/case to solve the long-awaited issue. This pattern matching would include names, literals, constant values, sequences, mapping, class among others including the popularly used conditional statements. The matches that are not possible or challenging to resolve will throw an exception at the runtime.

The objects in Python will be able to handle match texts in new ways, being known as the match protocol. So, let’s say that if an object implements the _match_ method, it will be used to test if matches a given class pattern. After which it returns an appropriate response.

Here is an example of what the pattern matching syntax of the PEP 622 version of Python will look like-



match cases:
   Case 0|1|2:
      print("Odd number")
    case [] | [_]:
        print("A sequence")
    case str() | bytes():
    case _:
        print("Anything else")

This proposed update for pattern matching would allow static checkers to validate the matches and ensure that they can be verified. The earlier PEP versions such as 275 and 3103 would be turned down by the users due to lack of adequate support. However, a positive response is expected from this version since it addresses one of the key issues of the language.


Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}