In some functional programming languages, they can pattern match a function
based on its parameters. Similar to function overloading. Will Python Pattern
Matching do something similar to functions?
If calling a function doesn't match any of the cases and catch-all case is not
present, then some sort of new or exisiting Exception needs to be raised.
Type annotations can be used (for the parameters, they may be redundant, but
for the return, they can be useful). The Return annotation comes right after
the guard.
See theortical example below.
class Point:
def __init__(self, pos):
self.pos = pos
def write(self, msg):
return f"writing {msg}"
match def f:
case (float(x) | int(x), float(y) | int(y)) if x > 0 -> int:
return round(x + y)
# f(3.4, 7) => 10
case (int(x) | float(x)):
return round(2 * x)
# f(8) => 16
case (0):
return 0
# f(0) => 0
case (0, 0):
return "Origin"
# f(0, 0) => "Origin"
case ([int(x) | float(x), int(y) | float(y)], int(z) | float(z)):
return x + y + z
# f((5, 2.5), 2.5) => 10
case (
(Point(pos=(int(x), int(y)))) as point,
*_,
message=str(msg),
**_,
) if x > 0 and y > 0:
txt = point.write(msg)
res = x + y
return res, txt
# point = Point([1, 9])
# f(point, message="Hello") => 10, "writing Hello"
case (*_, **_):
return "Catch_All"
## which can be shortened to...
case _:
return "Catch_All"
#f(1, 3, 4, 5) => “Catch_All"
_______________________________________________
Python-ideas mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at
https://mail.python.org/archives/list/[email protected]/message/3M4PDXEBQM2OROTFOZ6EZDFTZK2HM5NN/
Code of Conduct: http://python.org/psf/codeofconduct/