Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # coding: utf-8
- """
- This is an example using a class as a decorator.
- """
- class logexcept(object):
- """
- There are 2 cases for using this decorator. The first is without a
- call to @logexcept when decorating
- >>> @logexcept
- >>> def myfunc(*args, **kw):
- >>> ...
- This is equivalent to:
- >>> def myfunc(*args, **kw):
- >>> ...
- >>> myfunc = logexcept(myfunc)
- The second is when there s a call to @logexcept(...) when decorating
- the function.
- >>> @logexcept(...)
- >>> def myfunc(*args, **kw):
- >>> ...
- This is equivalent to:
- >>> def myfunc(*args, **kw):
- >>> ...
- >>> mydec = logexcept(...)
- >>> myfunc = mydec(myfunc)
- >>> # OR: myfunc = logexcept(...)(myfunc)
- """
- def __init__(self, *args, **kwargs):
- if args and callable(args[0]):
- '''
- We are doing:
- >>> @logexcept
- >>> def myfunc(...)
- '''
- self.func = args[0]
- else:
- '''
- We are doing:
- >>> @logexcept(...)
- >>> def myfunc(...)
- So *args and **kwargs are the arguments passed to logexcept, and
- myfunc will be passed in __call__
- '''
- self.func = None
- def __call__(self, *args, **kwargs):
- if self.func:
- '''
- Since we have func, this means we can just pass these args to
- myfunc because we're doing:
- >>> myfunc(...) # Call our wrapped function.
- '''
- return self.func(*args, **kwargs)
- else:
- '''
- Since we do not have func yet, this means we did:
- >>> @logexcept(...)
- >>> def myfunc(...)
- And this __call__ is where we're really wrapping myfunc:
- >>> def myfunc(...):
- >>> ...
- >>> mydec = logexcept(...) # <-- THIS WAS __init__
- >>> myfunc = mydec(myfunc) # <-- RIGHT NOW IS __call__
- '''
- if not args or not callable(args[0]):
- raise TypeError("Did not get callable, got %r and %r." % (args, kwargs))
- self.func = args[0]
- # The next time this is called, the first if statement will be ran.
- # Make sure to return self so that when decorating with arguments,
- # we actually get this wrapper instead of None.
- return self
- def __get__(self, obj, type=None):
- """
- This is extra binding logic making self (an instance of logexcept) a
- function descriptor so that decorating methods in classes work
- properly (i.e., they get passed self or cls properly).
- """
- self.func = self.func.__get__(obj, type)
- return self
Advertisement
Add Comment
Please, Sign In to add comment