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
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.