Decorators/wrappers

Decorators/wrappers




What is it?

In object-oriented programming, the decorator pattern (also known as Wrapper, an alternative naming shared with the Adapter pattern) is a design pattern that allows behavior to be added to an individual object, either statically or dynamically, without affecting the behavior of other objects from the same class.




Example for my case:
# Decorators
from functools import wraps


def my_logger(orig_func):
   import logging
   logging.basicConfig(filename='{}.log'.format(orig_func.__name__), level=logging.INFO)

   @wraps(orig_func)
   def wrapper(*args, **kwargs):
       logging.info(
           'Ran with args: {}, and kwargs: {}'.format(args, kwargs))
       return orig_func(*args, **kwargs)

   return wrapper


def my_timer(orig_func):
   import time

   @wraps(orig_func)
   def wrapper(*args, **kwargs):
       t1 = time.time()
       result = orig_func(*args, **kwargs)
       t2 = time.time() - t1
       print('{} ran in: {} sec'.format(orig_func.__name__, t2))
       return result

   return wrapper

import time


@my_logger
@my_timer
def display_info(name, age):
   time.sleep(1)
   print('display_info ran with arguments ({}, {})'.format(name, age))

display_info('Tom', 22)


Related concepts

  1. First class functions: allow us to treat functions and any other objects, i.e. as an argument for a function, return functions, assign function to variables. Tutorial: https://www.youtube.com/watch?v=kr0mpwqttM0
  2. Closures: allow us to pass function with remember local variables. Tutorial: https://www.youtube.com/watch?v=swU3c34d2NQ

First class function (FCC)

  1. The distinction is not that individual functions can be first class or not, but that entire languages may treat functions as first-class objects, or may not.
  2. A first-class function is not a particular kind of function.
  3. All functions in Python are first-class functions. To say that functions are first-class in a certain programming language means that they can be passed around and manipulated similarly to how you would pass around and manipulate other kinds of objects (like integers or strings).
  4. "First-Class Functions" (FCF) are functions which are treated as so called "First-Class Citizens" (FCC).
  5. FCC's in a programming language are objects (using the term "objects" very freely here) which:
    1. Can be used as parameters/arguments for another functio
# Python program to illustrate functions
# can be passed as arguments to other functions
def shout(text):
   return text.upper()

def whisper(text):
   return text.lower()

def greet(func):
   # storing the function in a variable
   greeting = func("Hi, I am created by a function passed as an argument.")
   print greeting

greet(shout)
greet(whisper)
Run on IDE Output

HI, I AM CREATED BY A FUNCTION PASSED AS AN ARGUMENT.
hi, i am created by a function passed as an argument.
    1. Can be used as a return value
    2. Can be assigned to variables


# Python program to illustrate functions
# Functions can return another function
def create_adder(x):
   def adder(y):
       return x+y
   return adder
add_15 = create_adder(15)
print add_15(10)


    1. Can be stored in data structures such as hash tables, lists, ...

References


Closure

Summary: you can return a function without executing by omitting parentheses.


def print_msg(msg):
# This is the outer enclosing function


   def printer():
# This is the nested function
       print(msg)


   return printer  # this got changed


# Now let's try calling this function.
# Output: Hello
another = print_msg("Hello")
another()


When do we have a closure?


As seen from the above example, we have a closure in Python when a nested function references a value in its enclosing scope.

The criteria that must be met to create closure in Python are summarized in the following points.

We must have a nested function (function inside a function).
The nested function must refer to a value defined in the enclosing function.
The enclosing function must return the nested function.

References

  1. https://www.programiz.com/python-programming/closure
  2. https://en.wikipedia.org/wiki/First-class_functionhttps://en.wikipedia.org/wiki/Decorator_pattern#Motivation

Videos

  1. Useful tutorial with examples for timing and created logs. https://www.youtube.com/watch?v=FsAPt_9Bf3U


Blogs


Comentarios

Entradas populares de este blog

Making MongoDB remotely available.

Reflecting about SIR models and some examples

Adicction and Decision Making: a brainy view.