📖
Docs
  • Hi there 👋
  • Python
    • Tutorial
      • Class
      • Context Managers
      • Iterators and Iterables and generators
      • Lambda Operator
      • Decorators
      • Lập trình Ä‘a luồng
      • Singleton
      • Logging
      • Best practices
    • Django
      • Lazy queryset
      • Sql injection
      • Transaction
    • Flask
    • Fastapi
  • Struct data and algorithms
    • Struct data
    • Algorithms
  • database
    • Nosql và RDBMS
    • Index sql
    • Inverted Index
    • Migrate database best
    • Datatype
  • Cache
    • Caching strategies
    • Cache replacement policies
  • Message queue
    • Message queue
  • Other
    • Clean code
    • Design pattern
    • Encode-decode
    • Security
    • Docker
    • Celery
  • deploy
    • Jenkins
Powered by GitBook
On this page
  1. Python
  2. Tutorial

Decorators

Function decorator đơn giản là wrapper của một function có sẵn

def test_decorator(test_func):

    def wrap_func():
        print("start")
        test_func()
        print("end")

    return wrap_func

@test_decorator
def my_func():
    print('run')
    
my_func()
# output
start
run
end
import time
import functools

# Define a decorator function to cache the result of a function with a timeout
def cache(timeout):
    memo = {}
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args):
            if args in memo and time.time() - memo[args]['time'] < timeout:
                return memo[args]['result']
            else:
                result = func(*args)
                memo[args] = {'result': result, 'time': time.time()}
                return result
        return wrapper
    return decorator
PreviousLambda OperatorNextLập trình đa luồng

Last updated 2 years ago