Created
March 13, 2016 20:25
-
-
Save learnitall/a21c52540c87e3fab246 to your computer and use it in GitHub Desktop.
Applying pre and post conditions into python using decorators
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
# Pre and Post conditions in Java are done through comments a programmer puts | |
# around methods, or by raising errors directly in a function. However, | |
# if a group of functions need the same pre and post conditions, copying and pasting code | |
# can get tedious. In Python this problem can be avoided through the use of | |
# decorators. A template is laid out below: | |
def checkConditions(func): | |
def wrapped(*args, **kwargs): | |
if not (precondition_bool_expression): | |
raise Exception(reason) | |
else: | |
result = func(*args, **kwargs) | |
if not (postcondition_bool_expression): | |
raise Exception(reason) | |
else: | |
return result | |
return wrapped | |
# If you know what args and kwargs are going to be passed to func and have them | |
# explicitly laid out in the declaration of wrapped, yet you still want to use | |
# the decorator on a method inside of a class: | |
def checkConditions(func): | |
def wrapped(self, arg1, arg2, arg3, etc): | |
if not (precondition_bool_expression): | |
raise Exception(reason) | |
else: | |
result = func(self, arg1, arg2, arg3, etc) | |
if not (postcondition_bool_expression): | |
raise Exception(reason) | |
else: | |
return result | |
return wrapped |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you!