Skip to content

Instantly share code, notes, and snippets.

@aflansburg
Created June 18, 2021 15:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aflansburg/2715fc2fe2330ef5f76a48f2c5df92c5 to your computer and use it in GitHub Desktop.
Save aflansburg/2715fc2fe2330ef5f76a48f2c5df92c5 to your computer and use it in GitHub Desktop.
Naive Use Case of Structural Pattern Matching (Python 3.10)
# https://www.python.org/dev/peps/pep-0634/
# PEP 634 proposed (and was accepted) Structural Pattern Matching (switch/case)
# for Python (available in 3.10) - as of this Gist,
# prerelease 3.10.0b2 is available
import inspect
F = [
lambda x,y: x+y,
lambda x: x+1,
lambda x,y,z: x*y*z,
lambda a,b,c,d: a+b+c+d,
]
_F = []
for f in F:
match len(inspect.getfullargspec(f).args):
case 1:
print('This lambda has 1 arg - OK\n')
case 2:
print('This lambda has 2 arg - OK\n')
case 3:
print('This lambda has 3 arg - OK\n')
case _:
_F.append(f)
F.remove(f)
print('Error: Incorrect number of arguments found in lambda structure - FAIL\n')
_sources = ['\n' + str(inspect.getsource(_f)) for _f in _F]
sources = ['\n' + str(inspect.getsource(f)) for f in F]
print(f'The following lambdas had incorrect signatures:\n{"".join(_sources)}')
print(f'The following lambdas passed the test:\n{"".join(sources)}')
# Output
'''
This lambda has 2 arg - OK
This lambda has 1 arg - OK
This lambda has 3 arg - OK
Error: Incorrect number of arguments found in lambda structure - FAIL
The following lambdas had incorrect signatures:
lambda a,b,c,d: a+b+c+d,
The following lambdas passed the test:
lambda x,y: x+y,
lambda x: x+1,
lambda x,y,z: x*y*z,
'''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment