using decorators with argument in Python/Django

42 views
Skip to first unread message

Jigar Tanna

unread,
Jun 28, 2011, 12:24:55 PM6/28/11
to django-d...@googlegroups.com
hey,

I am new to Python and Django, was going through the concept of decorators where I came across a special case of using arguments with decorators
Below is the code for memoization where I was looking at the concept...

cache = {}
def get_key(function, *args, **kw) :
    key = '%s. %s: ' % (function. __module__,function. __name__)
    hash_args = [ str(arg) for arg in args]
    hash_kw = [' %s: %s' % (k, hash(v) )
               for k, v in kw.items() ]
    return ' %s:: %s: : %s' % (key, hash_args, hash_kw)

def memoize(get_key=get_key, cache=cache) :
    def _memoize( function) :
        print function
        def __memoize(*args, **kw) :
            key = get_key(function, *args, **kw)
            try:
                return cache[key]
            except KeyError:
                cache[key] = function( *args, **kw)
                return cache[key]
        return __memoize
    return _memoize

@memoize()
def factory(n) :
    return n * n


# testcase
#print factory(3)
#
#


According to some of my collogues it is not a good practice to use decorators with arguments (i.e. @memoize() ) and instead it is good to just use @memoize. Can any of you guys explain me advantages and disadvantages of using each of them

Thanks ...

Tom Evans

unread,
Jun 28, 2011, 12:32:25 PM6/28/11
to django-d...@googlegroups.com

Not to rain too heavily on your parade, but:

1) Usage questions on django go to django-users@
2) Usage questions on python go to comp.lang.python
3) Only use django-developers@ if you intend on changing how django
itself is implemented.
4) Submitting the same question twice in such a short time to the same
mailing list is considered rude.

This doesn't even look like the django.utils.functional.memoize function.

Cheers

Tom

Jigar Tanna

unread,
Jun 28, 2011, 12:37:45 PM6/28/11
to Django developers
Sorry ... I understand .... will be careful ....may be i put it on a
wrong post ...

On Jun 28, 9:32 pm, Tom Evans <tevans...@googlemail.com> wrote:
Reply all
Reply to author
Forward
0 new messages