Login

More readable method annotations

Author:
eallik
Posted:
January 27, 2011
Language:
Python
Version:
Not specified
Score:
1 (after 3 ratings)

This is just a very thin layer of functionality for better readability. Does not have any effect on runtime performance.

 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. Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

Please login first before commenting.