Login

decorator for method attribute assignment

Author:
freality
Posted:
November 5, 2009
Language:
Python
Version:
1.1
Tags:
models decorator
Score:
0 (after 0 ratings)

A bit cleaner syntax for method attribute assignment; used in models for 'short_description'.

>from mysite.polls.models import Poll
>poll = Poll.objects.get(pk=1)
>poll.was_published_today.short_description

>>>'Published today?'
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
from django.db import models
from datetime import date

#function-type decorator
def addAttribute(attr, value):
    def wrap(meth):
        def wrapped(*args):
            return meth(*args)
        setattr(wrapped, attr, value)
        return wrapped
    return wrap

#class-type decorator
class set_attribute(object):
    def __init__(self, name, value):
        self.name = name 
        self.value = value
    
    def __call__(self, func):
        def wrapped(*args):
            return func(*args)
        setattr(wrapped, self.name, self.value)
        return wrapped

#USAGE
class Poll(models.Model):
    question = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')
    
    @set_attribute('short_description', 'Published today?')
    def was_published_today(self):
        return self.pub_date.date() == date.today()

More like this

  1. Finding related objects for instances in a queryset by akaihola 4 years, 2 months ago
  2. Custom managers with chainable filters by itavor 7 years, 4 months ago
  3. Model Choices Helper by pmclanahan 5 years, 3 months ago
  4. common model privacy by teepark 7 years, 9 months ago
  5. duplicate model object merging script by nstrite 7 years, 9 months ago

Comments

Please login first before commenting.