Hello Pythonistas,
I hope this message finds you well. I am relatively new to Python programming and have been working on enhancing my skills. Recently, I came across an intriguing concept while reading Fluent Python, 2nd Edition by Luciano Ramalho.
In Chapter 2, “An Array of Sequences,” the book discusses pattern matching with sequences and mentions that we can make patterns more specific by adding type information. The type information in patterns acts as runtime type checks, which sparked some ideas for me.
First Idea:
What if we use pattern matching to achieve stronger type checking within functions?
Here’s an example:
def function(*args):
match args:
case [str(), list(), tuple()]:
pass
case _:
raise TypeError("Function has been called with wrong arguments")
# Examples of usage
function(1) # Raises TypeError
function('', [], ()) # Works fine
function('0', [1], (2)) # Raises TypeError
function('0', [1], (2,)) # Works fine
As you can see, using pattern matching with type information (as mentioned in the book), the interpreter raises an exception if the function is called with arguments of the wrong types.
Second Idea:
Could we make this runtime type checking part of the interpreter itself?
I am curious if it would be feasible for the interpreter to use type information in match/case scenarios and apply the same logic when type hints are used in function definitions.
I would love to hear your thoughts on these ideas and their potential feasibility in future Python releases.
Thank you for your time and consideration.
Best regards,