On Wed, Jun 29, 2011 at 12:22 AM, Jigar Tanna <[email protected]> wrote: > 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
Firstly, this really isn't a question for django-developers -- it's probably not even a question for django-users, since it's a general Python question, not something that is Django-specific. Secondly, I have no idea why your colleagues would be advising against decorators with arguments. They work fine, and examples of decorators with arguments in Django, in the Python core, and in the PEP where decorators were introduced into Python as a language. Rejecting them universally sounds like dogma to me. The only reason I can think that you might advise against them is in the case where you aren't (and won't ever) actually using the arguments -- in that case, there's a minor performance penalty associated with the extra layer required to support the arguments. However, that's more a case of 'don't make things more complex than they need to be', rather than specific advice about decorators. Yours, Russ Magee %-) -- You received this message because you are subscribed to the Google Groups "Django developers" group. To post to this group, send email to [email protected]. To unsubscribe from this group, send email to [email protected]. For more options, visit this group at http://groups.google.com/group/django-developers?hl=en.
