Dekoratory i metadane

Pisanie funkcji w Pythonie

Shayne Miel

Software Architect @ Duo Security

def sleep_n_seconds(n=10):
  """Pause processing for n seconds.

  Args:
    n (int): The number of seconds to pause for.
  """
  time.sleep(n)

print(sleep_n_seconds.__doc__)
Pause processing for n seconds.

  Args:
    n (int): The number of seconds to pause for.
Pisanie funkcji w Pythonie
def sleep_n_seconds(n=10):
  """Pause processing for n seconds.

  Args:
    n (int): The number of seconds to pause for.
  """
  time.sleep(n)

print(sleep_n_seconds.__name__)
sleep_n_seconds
print(sleep_n_seconds.__defaults__)
(10,)
Pisanie funkcji w Pythonie
@timer
def sleep_n_seconds(n=10):
  """Pause processing for n seconds.

  Args:
    n (int): The number of seconds to pause for.
  """
  time.sleep(n)

print(sleep_n_seconds.__doc__)


print(sleep_n_seconds.__name__)
wrapper
Pisanie funkcji w Pythonie

Dekorator timer

def timer(func):
  """A decorator that prints how long a function took to run."""

  def wrapper(*args, **kwargs):
    t_start = time.time()

    result = func(*args, **kwargs)

    t_total = time.time() - t_start
    print('{} took {}s'.format(func.__name__, t_total))

    return result

  return wrapper
Pisanie funkcji w Pythonie
from functools import wraps

def timer(func): """A decorator that prints how long a function took to run.""" @wraps(func) def wrapper(*args, **kwargs):
t_start = time.time() result = func(*args, **kwargs) t_total = time.time() - t_start print('{} took {}s'.format(func.__name__, t_total)) return result
return wrapper
Pisanie funkcji w Pythonie
@timer
def sleep_n_seconds(n=10):
  """Pause processing for n seconds.

  Args:
    n (int): The number of seconds to pause for.
  """
  time.sleep(n)

print(sleep_n_seconds.__doc__)
Pause processing for n seconds.

  Args:
    n (int): The number of seconds to pause for.
Pisanie funkcji w Pythonie
@timer
def sleep_n_seconds(n=10):
  """Pause processing for n seconds.

  Args:
    n (int): The number of seconds to pause for.
  """
  time.sleep(n)

print(sleep_n_seconds.__name__)
sleep_n_seconds
Pisanie funkcji w Pythonie

Dostęp do oryginalnej funkcji

@timer
def sleep_n_seconds(n=10):
  """Pause processing for n seconds.

  Args:
    n (int): The number of seconds to pause for.
  """
  time.sleep(n)

sleep_n_seconds.__wrapped__
<function sleep_n_seconds at 0x7f52cab44ae8>
Pisanie funkcji w Pythonie

Czas na ćwiczenia!

Pisanie funkcji w Pythonie

Preparing Video For Download...