Created
June 26, 2012 07:52
-
-
Save amitsaha/2994220 to your computer and use it in GitHub Desktop.
Using Decorators for implementing Function Sentinels
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/python | |
| #decorator function | |
| def sentinel(lst,integer): | |
| def wrap(f): | |
| def wrapped_f(*args): | |
| if args[0].__class__ is list and args[1].__class__ is int: | |
| print 'Valid call to {0:s}'.format(f.func_name) | |
| f(args[0],args[1]) | |
| else: | |
| print 'Invalid call to {0:s}'.format(f.func_name) | |
| return wrapped_f | |
| return wrap | |
| @sentinel(['foo','bar'],5) | |
| def fnc1(lst, integer): | |
| print lst, integer | |
| @sentinel(['foo','bar'],5) | |
| def fnc2(lst, integer): | |
| print lst, integer | |
| #entry point | |
| if __name__ == '__main__': | |
| fnc1([1,2],5) | |
| fnc1([1,2],'a') | |
| fnc2([1,2],'a') | |
| # Sample output: | |
| $ python func_sentinel.py | |
| Valid call to fnc1 | |
| [1, 2] 5 | |
| Invalid call to fnc1 | |
| Invalid call to fnc2 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment