Created
April 5, 2019 09:37
-
-
Save NoFishLikeIan/d1f0de08d7291c69b84a3850283d0033 to your computer and use it in GitHub Desktop.
A simple python decorator that prevents calling functions if other class attributes are not set. Beware this breaks the "Errors should never pass silently" rule!
This file contains 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
from functools import wraps | |
def has_all_attr(self, *attribute_names): | |
''' | |
An aid function to determine the condition of "not calling", this could be a parameter of conditional on potentially | |
''' | |
return all((hasattr(self, attr) and getattr(self, attr) is not None) for attr in attribute_names) | |
def conditional_on(*parameters): | |
def decorator(func): | |
@wraps(func) | |
def wrapper(self, *args, **kwargs): | |
if has_all_attr(self, *parameters): | |
func(self, *args, **kwargs) | |
return wrapper | |
return decorator | |
if __name__ == '__main__': | |
# It works as follows | |
class Foo: | |
def __init__(self, cond = None): | |
self.cond = cond | |
@cond('cond') | |
def conditionated(self): | |
print('Hello world!') | |
non_calling_foo = Foo() | |
# The following function will not be called | |
non_calling_foo.condtionated() | |
calling_foo = Foo(3) | |
# The following function will print "Hello world!" | |
calling_foo.conditionated() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment