"Structural pattern matching" for Python, part 2
"Structural pattern matching" for Python, part 2
Posted Sep 10, 2020 2:12 UTC (Thu) by milesrout (guest, #126894)In reply to: "Structural pattern matching" for Python, part 2 by johill
Parent article: "Structural pattern matching" for Python, part 2
That's quite intentional. If you are passing the wrong type of value to a function then your code should crash. The code will also crash if I pass a string to a function that expects an integer. Code should not be full of defensive checks for programmer error: they're code paths that are hard if not impossible to test and by design are intended to never be run (nobody makes programmer errors on purpose). Type checks are for dispatching based on type in Python, and most of the time 'isinstance' checks are the wrong way of doing things. "if isinstance elif isinstance elif isinstance"-style code is considered unPythonic, and I don't think that papering over that code with a language construct makes it a good idea.
Now there are possibly some cases where you want to be able to pass different sizes of tuples to a single function. However I think in most of those cases you probably shouldn't be using tuples, you should be using something like a named tuple, a dictionary, a custom class, a dataclass with an optional field, or just separate arguments to a single function, some of which are optional.
Or possibly you should actually be making a decision 'am I working with 2-tuples or 3-tuples?' at a higher level and switch. If you had some code that is meant to work with 2D or 3D or 4D vectors for example, it would be better to have separate functions for the length of 2D, 3D and 4D vectors than a single function that does
def veclen(v):
match v:
case (x,y): return sqrt(x*x + y*y)
case (x,y,z): return sqrt(x*x + y*y + z*z)
case (x,y,z,w): return sqrt(x*x + y*y + z*z + w*w)
Then you should make the determination as to whether you are working with 2D, 3D or 4D vectors at a high level and write all the functions dealing with 2D, 3D or 4D vectors separately.
For example if you really want to write 'length-agnostic' code with tuples up to some maximum length, then you should encapsulate that variation in size in Vector2D, Vector3D and Vector4D etc. classes with a common Vector superclass such that Vector's methods can be those that are parametric in the dimension.
And if it's really truly length-agnostic tuple code then you should be writing loops over lists, not matching on tuples.
