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.
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.
Any variable attribute of an object can be used as a value pattern.
Let us understand with an example
Here is the output in different cases of subject
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
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
Here are different types of outputs
The * can also be used in combination with wildcard _. Ex: case 'a', *_
These patterns use single underscore _ to match a part of or whole subject.
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)
For a scenario where the subject should only include the pattern, We can make use of a guard.
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.