In this final blog of the series, we conclude our discussion with the introduction of Class Pattern.
In our first 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.
In the second blog, we discussed value patterns, sequence patterns, and mapping patterns.
In this blog we talk about class pattern matching.
Matching a class pattern with no arguments depends on if an instance call is a success or not.
Let us understand with an example:
If a python class without class attribute __match_args__ is used as a class pattern and has arguments in the class pattern, Will result in TypeError.
In the above example, even though the subject Furniture("table", 2200) and pattern for 1st case Furniture("table", 2200) are the same it’s not a match as the order of positional argument doesn’t match with __match_args__ attribute, while it matches with 2nd case Furniture(2200, "table")
To make things easier w.r.t order of argument or the __match_args__ attribute, data classes, or named tuples can be used as these classes will already have this attribute.
For a data class, the order of __match_args__ is the same as to order in its constructor(Or while declaring a data class). In a data class if the init field param of an attribute is False, then this attribute will not be included in the __match_args__ tuple.
For some built-in types the positional arguments/sub patterns are not matched as we have seen earlier, These types include: primitive data types like: str. int, float, and bool collection data types like list, tuple, set, and dict Also bytes, frozen set, byte array
When a class pattern is declared using these above built-in types only one argument I allowed for the pattern, which then gets assigned a value of the subject if the subject matches the pattern.
If more than 1 argument/sub pattern is passed to such builtin types it will result in a TypeError
In this 3 part series, we introduced the structured python matching feature introduced in Python 3.10. While SPM is generally considered a feature of functional and hybrid programming languages, Python embracing SPM opens up new possibilities for structuring the codebase. However, it remains to be seen how much of this feature is adopted by the Python community.