diff --git a/07_python/bench.py b/07_python/bench.py new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/07_python/bench.py @@ -0,0 +1 @@ + diff --git a/07_python/closure.py b/07_python/closure.py new file mode 100644 index 0000000..66c714b --- /dev/null +++ b/07_python/closure.py @@ -0,0 +1,9 @@ +def adder(): + n = 0 + + def add(): + nonlocal n + n += 1 + return n + + return add diff --git a/07_python/debugger.py b/07_python/debugger.py new file mode 100644 index 0000000..dd7bb51 --- /dev/null +++ b/07_python/debugger.py @@ -0,0 +1,14 @@ +def debug_call(f): + def inner(*args, **kwargs): + print(f, args, kwargs) + return f(*args, **kwargs) + + return inner + + +# @debug_call +def foo(a, b): + return a + b + + +foo = debug_call(foo) diff --git a/07_python/name_test.py b/07_python/name_test.py new file mode 100644 index 0000000..6e4f9f0 --- /dev/null +++ b/07_python/name_test.py @@ -0,0 +1,77 @@ +# first attempt +def deco_first(f): + def inner(*args, **kwargs): + return f(*args, **kwargs) + + inner.__name__ = f.__name__ + inner.__doc__ = f.__doc__ + inner.__qualname__ = f.__qualname__ + + return inner + + +# second attempt +from functools import update_wrapper + + +def deco_second(f): + def inner(*args, **kwargs): + return f(*args, **kwargs) + + update_wrapper(inner, f) + return inner + + +# third attempt + + +def my_wraps(original): + def deco(wrapper): + update_wrapper(wrapper, original) + return wrapper + + return deco + + +from functools import partial + + +def partial_wraps(original): + return partial(update_wrapper, wrapped=original) + + +# def deco_third(f): +# def inner(*args, **kwargs): +# return f(*args, **kwargs) +# +# deco = my_wraps(f) +# inner = deco(inner) +# return inner + + +def deco_third(f): + @partial_wraps(f) + def inner(*args, **kwargs): + return f(*args, **kwargs) + + return inner + + +# third attempt +from functools import wraps + + +def deco_fourth(f): + @wraps(f) + def inner(*args, **kwargs): + return f(*args, **kwargs) + + return inner + + +@deco_third +def foo(a, b, c): + """ + Foo function docstring + """ + return a + b + c diff --git a/07_python/partial.py b/07_python/partial.py new file mode 100644 index 0000000..bcfad57 --- /dev/null +++ b/07_python/partial.py @@ -0,0 +1,8 @@ +from functools import partial + + +def foo(a, b, new_name): + return new_name * (b + a) + + +bar = partial(foo, c=500) diff --git a/07_python/retry.py b/07_python/retry.py new file mode 100644 index 0000000..47753d2 --- /dev/null +++ b/07_python/retry.py @@ -0,0 +1,33 @@ +def adder(): + n = 0 + + def add(): + nonlocal n + n += 1 + return n + + return add + + +def retry(n: int = 5): + def deco(f): + def inner(*args, **kwargs): + for _ in range(n): + f(*args, **kwargs) + + return inner + + return deco + + +# @retry(5) +def foo(): + print("Hello world!") + + +foo = (retry(5))(foo) + + +@retry(15) +def bar(): + print("Bar")