Skip to content

Instantly share code, notes, and snippets.

@santa4nt
Created May 27, 2011 18:17
Show Gist options
  • Select an option

  • Save santa4nt/995819 to your computer and use it in GitHub Desktop.

Select an option

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.
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