Add python decorators seminar

main
Aleksey Zubakov 2 years ago
parent e8c503d7b6
commit 6e72f80aa6
  1. 1
      07_python/bench.py
  2. 9
      07_python/closure.py
  3. 14
      07_python/debugger.py
  4. 77
      07_python/name_test.py
  5. 8
      07_python/partial.py
  6. 33
      07_python/retry.py

@ -0,0 +1,9 @@
def adder():
n = 0
def add():
nonlocal n
n += 1
return n
return add

@ -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)

@ -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

@ -0,0 +1,8 @@
from functools import partial
def foo(a, b, new_name):
return new_name * (b + a)
bar = partial(foo, c=500)

@ -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")
Loading…
Cancel
Save