On Tue, Nov 17, 2020 at 08:49:28AM +0100, Marco Sulla wrote:
> PS: pattern matching, for a mere mortal like me, seems to be something very
> exotical.
Have you ever written code that looks like this?
if isinstance(obj, tuple) and len(obj) ==3:
x, y, z = obj
elif isinstance(obj, tuple) and len(obj) == 2:
x, y = obj
z = 0.0
elif isinstance(obj, float):
x = obj
y = z = 0.0
else:
raise ValueError
process(x, y, z)
That's pattern matching.
match obj:
case x, y, z:
pass
case x, y:
z = 0.0
case x if isinstance(x, float):
y = z = 0.0
case _:
raise ValueError
process(x, y, z)
There may be cleaner or alternative ways to write this as a match
statement, I'm still learning pattern matching idioms myself. But in a
nutshell, they simplify what would otherwise look like a long,
repetitive chain of if, isinstance, sequence unpacking, etc.
--
Steve
_______________________________________________
Python-Dev mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3/lists/python-dev.python.org/
Message archived at
https://mail.python.org/archives/list/[email protected]/message/SVWBK5PJISLMPEZ7CHM2HVLGFTGQJKIZ/
Code of Conduct: http://python.org/psf/codeofconduct/