Created
May 27, 2011 18:17
-
-
Save santa4nt/995819 to your computer and use it in GitHub Desktop.
A decorator to check a method's object attribute before executing its body.
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
| def check(attr): | |
| def _check_fn(fn): | |
| """Use this function as a method decorator. When decorated with this, a | |
| method will only execute its body when its associated object's attribute | |
| is defined (evaluates to True). | |
| """ | |
| def meth(self, *args, **kwargs): | |
| if getattr(self, attr, None): | |
| return fn(self, *args, **kwargs) | |
| return meth | |
| return _check_fn | |
| class Foo(object): | |
| def __init__(self, _foo): | |
| self._foo = _foo | |
| @check('_foo') | |
| def foo(self): | |
| """Examples: | |
| >>> from decometh import Foo | |
| >>> f = Foo('Hello') | |
| >>> f.foo() | |
| 'Hello' | |
| >>> f = Foo(None) | |
| >>> f.foo() | |
| >>> | |
| """ | |
| return self._foo |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment