Login

Wrapper-function Pattern

Author:
Archatas
Posted:
April 14, 2010
Language:
Python
Version:
1.1
Score:
0 (after 0 ratings)

This is an example how to create a wrapping function that can read all incoming arguments, do something with them and then call the original function. This pattern works well with generic views.

Note that wrapper function accepts arguments in both ways: as a list of unnamed arguments and as a list of keyword-value pairs.

A real-world example:

def published_object_list(request, *args, **kwargs):
    arg_names = object_list.func_code.co_varnames
    params = dict(zip(arg_names, args))
    params.update(kwargs)

    params['queryset'] = params['queryset'].filter(is_published=True)
    if request.is_ajax():
        params['template_name'] = "ajax/" + params['template_name']

    return object_list(request, **params)
1
2
3
4
5
6
7
8
9
def wrapper_function(*args, **kwargs):
    arg_names = original_function.func_code.co_varnames
    params = dict(zip(arg_names, args))
    params.update(kwargs)
    
    # now you have args and kwargs collected to the dictionary params
    # you can read and modify them here and then call the original function
    
    return original_function(**params)

More like this

  1. get_object_or_none by azwdevops 1 month, 4 weeks ago
  2. Mask sensitive data from logger by agusmakmun 3 months, 3 weeks ago
  3. Template tag - list punctuation for a list of items by shapiromatron 1 year, 6 months ago
  4. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 1 year, 6 months ago
  5. Serializer factory with Django Rest Framework by julio 2 years, 1 month ago

Comments

Please login first before commenting.