More readable method annotations

 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
def annotate(**kwargs):
    def wrap(func):
        for name, value in kwargs.iteritems():
            # We're annotating, and annotating doesn't mean
            # overwriting/redegining existing attributes.
            #
            # We wouldn't need this assertion if the function were set_attrs.
            assert not hasattr(func, name)
            setattr(func, name, value)
        return func
    return wrap



class MyModel(models.Model):
    foo = models.CharField(...)
    bar = models.CharField(...)

    # OLD:
    def foobar(self):
        return '<a href="%s">%s</a>' % (self.foo, self.bar)
    foobar.short_description = 'Returns the foobar'
    foobar.allow_tags = True

    # NEW:
    @annotate(short_description='Returns the foobar',
              allow_tags=True)
    def foobar(self):
        return '<a href="%s">%s</a>' % (self.foo, self.bar)

More like this

  1. Class Feeds DRY TemplateTag by gmandx 3 years, 1 month ago
  2. decorator to synchronize method at class / module level by mwolgemuth 4 years, 4 months ago
  3. Digg Style URL String Parser by addicted 6 years, 2 months ago
  4. Complex Form Preview by smagala 4 years, 2 months ago
  5. Compact P3P policy header injection middleware by mwolgemuth 4 years, 8 months ago

Comments

(Forgotten your password?)