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

Implementing feature flags for controlled rollouts and experimentation in production

Discover how feature flags can revolutionize your software deployment strategy in this comprehensive guide. Learn to implement everything from basic toggles to sophisticated experimentation platforms with practical code examples in Java, JavaScript, and Node.js. The post covers essential implementation patterns, best practices for flag management, and real-world architectures that have helped companies like Spotify reduce deployment risks by 80%. Whether you're looking to enable controlled rollouts, A/B testing, or zero-downtime migrations, this guide provides the technical foundation you need to build robust feature flagging systems.

time
12
 min read

Implementing incremental data processing using Databricks Delta Lake's change data feed

Discover how to implement efficient incremental data processing with Databricks Delta Lake's Change Data Feed. This comprehensive guide walks through enabling CDF, reading change data, and building robust processing pipelines that only handle modified data. Learn advanced patterns for schema evolution, large data volumes, and exactly-once processing, plus real-world applications including real-time analytics dashboards and data quality monitoring. Perfect for data engineers looking to optimize resource usage and processing time.

time
12
 min read

Implementing custom embeddings in LlamaIndex for domain-specific information retrieval

Discover how to dramatically improve search relevance in specialized domains by implementing custom embeddings in LlamaIndex. This comprehensive guide walks through four practical approaches—from fine-tuning existing models to creating knowledge-enhanced embeddings—with real-world code examples. Learn how domain-specific embeddings can boost precision by 30-45% compared to general-purpose models, as demonstrated in a legal tech case study where search precision jumped from 67% to 89%.

time
15
 min read