/python-awesome-decorators

List of useful decorators for Python

Primary LanguagePythonMIT LicenseMIT

Awesome decorators

Build Status Coverage Status Maintainability Code Health

List of awesome decorators that could be useful in Python projects.

Installation

pip install python-awesome-decorators

Decorators

memoized

Return a property attribute for new-style classes that only calls its getter on the first access. The result is stored and on subsequent accesses is returned, preventing the need to call the getter any more.

from awesomedecorators import memoized

class Example:
  @memoized
  def my_property(self):
    # Do something that takes time and we want it to happen once

timeit

Return the time taken by a function to complete.

from awesomedecorators import timeit

@timeit
def myfunc(a):
  return a + 5

result, elapsed = myfunc(10)
print('this function took {} ms'.format(elapsed))

timeout

Raise a TimeoutError exception if a function does not complete before a certain duration specified in seconds.

import time
from awesomedecorators import timeout

@timeout(2)
def myfunc(duration):
    time.sleep(duration)

try:
  myfunc(3)
except TimeoutError:
  print('Time out !')
  pass