Structural Pattern Matching in Python II

In this blog, which is a second of a three-part series, we continue our discussion and introduce value pattern, sequence pattern, and mapping pattern.

GraphQL has a role beyond API Query Language- being the backbone of application Integration
background Coditation

Structural Pattern Matching in Python II

In the previous blog, we discussed the structured pattern matching feature in Python 3.10 where we explain literal patterns, capture patterns, wildcard patterns, AS patterns, OR patterns, and guard patterns.

Value Pattern matching

Any variable attribute of an object can be used as a value pattern.

Let us understand with an example


def value_patterns(subject):

    class Fuel():
        DIESEL = 'diesel'

    fuel = 'petrol'    

    match subject:
        case Fuel.DIESEL:
            print("What are diesel prices these days?")  
        case fuel:
            print(f"{fuel} won't do, my car runs on diesel.")

Here is the output in different cases of subject


    subject = "water" # Output: water won't do, my car runs on diesel.
    subject = "diesel" # Output: What are diesel prices these days?

For a more standardized way, we can use named tuples, data classes, and enums.

If a pre-defined variable is used, it will be considered as an irrefutable pattern and used as a capture pattern as shown in the above example

Sequence Pattern matching

Any object that inherits from collections. abc. The sequence is eligible to be matched as a sequence pattern except for str, bytes, byte array, and iterators


def sequence_patterns(subject):

    match subject:
        case 'a', *tail:
            print(f"The trailing values after a are {tail}")
        case ('H', *mid, 'd'):
            print(f"The subject starts with H and ends with d")

Here are different types of outputs


    subject = ['a',(2, 3)] # Output: The trailing values after a are [(2, 3)]
    subject = list("HelloWorld") # Output: The subject starts with H and ends with d

  • variable_name can be used to get an unknown number of elements.

The * can also be used in combination with wildcard _. Ex: case 'a', *_

Mapping Pattern matching

These patterns use single underscore _ to match a part of or whole subject.


subject = {'id': 1, 'name': 'Apple'} # Output: Apple is a fruit

match subject:
    case {'name': 'Apple'}:
        print("Apple is a fruit")
    case {'id': 1, 'name': 'Apple'}:
        print("We found an Apple with id 1")

While matching a mapping pattern not all parts(key-value pairs) of the subject need to be present in the pattern. As we can see in the above example the 1st case {'name': 'Apple'} was a successful match of the subject. To keep track of extra key-value pairs or items-pattern we can use ** with a free variable(capture pattern)


subject = {'name': 'Apple', 'colour': 'Red'} # Output: The other properties of Apple are {'colour': 'Red'}

match subject:
    case {'name': 'Apple', **extras}:
        print(f"The other properties of Apple are {extras}")

For a scenario where the subject should only include the pattern, We can make use of a guard.



subject = {'name': 'Apple', 'colour': 'Red'} # Output: I found a red apple

match subject:
    case {'name': 'Apple', **extras} if not extras:
        print("Apple is a fruit")
    case {'name': 'Apple', 'colour': 'Red', **extras} if not extras:
        print("I found a red apple")
        

get() method of an object(subject) is used for matching the mapping pattern. A get() method can only fetch a key if it already exists in the subject, Hence subjects with class defaultdict no new keys will be created if not found and won’t be a successful match.

That concludes part 2 of the structured pattern matching in the python series. In the next blog, we close the discussion with Class Pattern.

Hi, I am Harris Hujare. As a software developer, I design and implement scalable and maintainable systems. I have a passion for learning new technologies and creating software utilities making lives easier.

Want to receive update about our upcoming podcast?

Thanks for joining our newsletter.
Oops! Something went wrong.

Latest Articles

Designing multi-agent systems using LangGraph for collaborative problem-solving

Learn how to build sophisticated multi-agent systems using LangGraph for collaborative problem-solving. This comprehensive guide covers the implementation of a software development team of AI agents, including task breakdown, code implementation, and review processes. Discover practical patterns for state management, agent communication, error handling, and system monitoring. With real-world examples and code implementations, you'll understand how to orchestrate multiple AI agents to tackle complex problems effectively. Perfect for developers looking to create robust, production-grade multi-agent systems that can handle iterative development workflows and maintain reliable state management.

time
7
 min read

Designing event-driven microservices architectures using Apache Kafka and Kafka Streams

Dive into the world of event-driven microservices architecture with Apache Kafka and Kafka Streams. This comprehensive guide explores core concepts, implementation patterns, and best practices for building scalable distributed systems. Learn how to design event schemas, process streams effectively, and handle failures gracefully. With practical Java code examples and real-world architectural patterns, discover how companies like Netflix and LinkedIn process billions of events daily. Whether you're new to event-driven architecture or looking to optimize your existing system, this guide provides valuable insights into building robust, loosely coupled microservices.

time
12
 min read

Implementing Custom Instrumentation for Application Performance Monitoring (APM) Using OpenTelemetry

Application Performance Monitoring (APM) has become crucial for businesses to ensure optimal software performance and user experience. As applications grow more complex and distributed, the need for comprehensive monitoring solutions has never been greater. OpenTelemetry has emerged as a powerful, vendor-neutral framework for instrumenting, generating, collecting, and exporting telemetry data. This article explores how to implement custom instrumentation using OpenTelemetry for effective APM.

Mobile Engineering
time
5
 min read