Login

More readable method annotations

Author:
eallik
Posted:
January 27, 2011
Language:
Python
Version:
Not specified
Tags:
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. Retrieve human-readable value from choices tuple or value from dict by JoeLinux 2 years ago
  2. Paths in Django settings relative to settings.py by zejn 7 years, 4 months ago
  3. Human format Date representation by sachingupta006 2 years, 11 months ago
  4. More readable Enumeration class for Django choices by achimnol 5 years, 7 months ago
  5. SizeAndTimeMiddleware by amitu 6 years, 4 months ago

Comments

Please login first before commenting.