58 lines
1.7 KiB
Python
58 lines
1.7 KiB
Python
from collections import defaultdict
|
|
from functools import wraps
|
|
|
|
def infinitedict():
|
|
d = lambda: defaultdict(d)
|
|
return defaultdict(d)
|
|
|
|
def debugger(func):
|
|
@wraps(func)
|
|
def wrapper_debug(*args, **kwargs):
|
|
args_repr = [repr(arg) for arg in args]
|
|
kwargs_repr = [f"{key}={value!r}" for key, value in kwargs.items()]
|
|
signature = ", ".join(args_repr + kwargs_repr)
|
|
print(f"[DEBUGGER]: Calling {func.__name__}({signature})")
|
|
result = func(*args, **kwargs)
|
|
print(f"[DEBUGGER]: {func.__name__!r} returned {result!r}")
|
|
return result
|
|
return wrapper_debug
|
|
|
|
def coroutine(func):
|
|
@wraps(func)
|
|
def wrapper_coroutine(*args, **kwargs):
|
|
coro = func(*args, **kwargs)
|
|
coro.__next__()
|
|
return coro
|
|
return wrapper_coroutine
|
|
|
|
def generator(func):
|
|
@wraps(func)
|
|
def wrapper_generator(*args, **kwargs):
|
|
try:
|
|
while True:
|
|
yield from func(*args, **kwargs)
|
|
except GeneratorExit:
|
|
pass
|
|
return coroutine(wrapper_generator)
|
|
|
|
def singleton(cls):
|
|
@wraps(cls)
|
|
def wrapper_singleton(*args, **kwargs):
|
|
if not wrapper_singleton.instance:
|
|
wrapper_singleton.instance = cls(*args, **kwargs)
|
|
return wrapper_singleton.instance
|
|
wrapper_singleton.instance = None
|
|
return wrapper_singleton
|
|
|
|
def curry(func, argc=None):
|
|
if argc is None:
|
|
argc = func.func_code.co_argcount
|
|
@wraps(func)
|
|
def wrapper_curry(*args):
|
|
if len(args) == argc:
|
|
return func(*args)
|
|
def curried(*c_args):
|
|
return func(*(args + c_args))
|
|
return curry(curried, argc - len(args))
|
|
return wrapper_curry
|