Snippets Collections
import functools


def singleton(cls):
    cls._instance = None

    @functools.wraps(cls)
    def wrapper_singleton(*args, **kwargs):
        if not cls._instance:
            cls._instance = cls(*args, **kwargs)
        return cls._instance

    return wrapper_singleton
import functools
import time
from typing import Callable, Any


def async_timed():
    def wrapper(func: Callable) -> Callable:

    @functools.wraps(func)
    async def wrapped(*args, **kwargs) -> Any:
        print(f'выполняется {func} с аргументами {args} {kwargs}')
        start = time.time()
        try:
            return await func(*args, **kwargs)
        finally:
            end = time.time()
            total = end - start
            print(f'{func} завершилась за {total:.4f} с')
        return wrapped
    return wrapper
def async_session(func):
    async def wrapper(*args, **kwargs):
        async with get_async_session() as session:
            return await func(session, *args, **kwargs)

    return wrapper
def check_permission(user):
    def decorator(func):
        def wrapper(*args, **kwargs):
            if user["access_level"] == "admin":
                return func(*args, **kwargs)

            raise Exception("No way!!!")

        return wrapper

    return decorator


user = {"username": "jose", "access_level": "admin"}


@check_permission(user)
def get_admin_pass():
    return "1234"


print(get_admin_pass())
def log_params(func):
    def wrapper(*args, **kwargs):
        return_value = func(*args, **kwargs)
        print(f"{args} -> {return_value}")

    return wrapper


@log_params
def summation(a: int, b: int) -> int:
    return a + b


summation(10, 20)
from datetime import datetime


def logger(func):
    def wrapper(*args, **kwargs):
        print('_' * 25)
        print(f'Run on: {datetime.today().strftime("%Y-%m-%d %H:%M:%S")}')
        print(f'Running function: {func.__name__}')
        func(*args, **kwargs)
        print('_' * 25)
    return wrapper
from time import time


def measure_time(func):
    def wrapper(*args, **kwargs):
        start = time()
        result = func(*args, **kwargs)
        print(f'Elapsed time is {time() - start} ms')
        return result
    return wrapper
star

Thu Jun 22 2023 13:39:52 GMT+0000 (Coordinated Universal Time)

#python #decorator
star

Sun Mar 12 2023 16:15:11 GMT+0000 (Coordinated Universal Time)

#python #decorator #timing
star

Tue Feb 14 2023 15:48:55 GMT+0000 (Coordinated Universal Time)

#python #decorator
star

Tue Jan 31 2023 10:14:18 GMT+0000 (Coordinated Universal Time)

#python #decorator
star

Mon Nov 14 2022 10:45:32 GMT+0000 (Coordinated Universal Time)

#python #decorator
star

Mon Jan 31 2022 02:23:59 GMT+0000 (Coordinated Universal Time)

#python #decorator
star

Mon Jan 31 2022 02:19:07 GMT+0000 (Coordinated Universal Time)

#python #decorator

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension