Skip to content

Instantly share code, notes, and snippets.

@apalii
Last active October 1, 2015 09:03
Show Gist options
  • Save apalii/3fe2f5072c96f08956bb to your computer and use it in GitHub Desktop.
Save apalii/3fe2f5072c96f08956bb to your computer and use it in GitHub Desktop.
>>> def decorate(func):
... print u"Декорируем %s..." % func.__name__,
... def wrapped(*args, **kwargs):
... print "Вызываем обёрнутую функцию с аргументами:", args
... return func(*args, **kwargs)
... print u"выполнено!"
... return wrapped
import logging
def method_decorator(func):
def wrapper(self, *argv, **kwargv):
logging.basicConfig(filename='myapp.log', level=logging.INFO)
logging.info(func.__doc__)
return func(self, *argv, **kwargv)
return wrapper
class Something1(object):
@method_decorator
def method1(self):
"""documentation thru method decorator for method 1"""
pass
def method2(self):
"""documentation thru method decorator for method 2"""
pass
@method_decorator
def method3(self):
"""documentation thru method decorator for method 3"""
pass
s1 = Something1()
s1.method1()
s1.method2()
s1.method3()
# or thru class decorator
def class_decorator(cls):
for name, method in cls.__dict__.iteritems():
if not name.startswith('_'):
setattr(cls, name, method_decorator(method))
return cls
@class_decorator
class Something2(object):
def method1(self):
"""documentation thru class decorator for method 1"""
pass
def method2(self):
"""documentation thru class decorator for method 2"""
pass
def method3(self):
"""documentation thru class decorator for method 3"""
pass
s2 = Something2()
s2.method1()
s2.method2()
s2.method3()
#check mixed execution
s1.method1()
s2.method1()
# -----------------------------------------
>>> def decorate(function_to_be_decorated):
... def another_function(num, den):
... if den==0:
... return 0
... else:
... return function_to_be_decorated(num, den)
... return another_function
>>> @decorate
... def divide(numerator, denominator):
... return numerator/denominator
----------------------------------------
import time
def timer(wrapped):
def inner(*args, **kwargs):
before = time.time()
ret = wrapped(*args, **kwargs)
print "The execution of " + wrapped.__name__ + " took {0:.3f}s".format(time.time() - before)
return ret
return inner
@timer
def foo(x):
time.sleep(3)
print x
@timer
def foo(x):
time.sleep(3)
print x
foo('hello')
or
def method_decorator(func):
def wrapper(self, *argv, **kwargv):
return func(self, *argv, **kwargv)
return wrapper
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment