example of programatic getters

20 November 2008
14:49

By brian as Python

1 class Mp3File(object):
2
3 # ...
4
5 # Translate names to appropriate tag.
6 _tags = {'album' : 'TALB',
7 'title' : 'TIT2',
8 'artist': 'TPE1',
9 'tracknumber' : 'TRCK',
10 'genre' : 'TCON'}
11
12 for name,tag in _tags.items():
13 def getter(self, tag=tag):
14 val = self.tags.get(tag, None)
15 return val and val.text[0] or None
16
17 def setter(self, value, tag=tag):
18 self.tags[tag] = getattr(id3, tag)(text=value, encoding=3)
19 self.tags.save()
20
21 locals()[name] = property(getter, setter)
22
23 del name, tag
24

Download Raw Source

Comments

  1. brian says:

    20 November 2008
    14:59

    I should have added a "del getter, setter" to the end there as well to get rid of the temporary functions.