Mercurial > hg > pyloader
comparison pyloader/factory.py @ 9:ff634cc2e62b
unfinished sketch of an abstract factory
author | Jeff Hammel <jhammel@mozilla.com> |
---|---|
date | Thu, 26 May 2011 18:14:56 -0700 |
parents | |
children | ba2355d57998 |
comparison
equal
deleted
inserted
replaced
8:4d3ea44fd813 | 9:ff634cc2e62b |
---|---|
1 """ | |
2 abstract factories | |
3 """ | |
4 | |
5 import loader | |
6 | |
7 class CircularReferenceError(Exception): | |
8 """factory has detected a circular reference""" | |
9 | |
10 class PyFactory(object): | |
11 | |
12 delimeters = ('%(', ')s') | |
13 | |
14 def __init__(self, config=None, main=''): | |
15 self.main = main # main section | |
16 self.seen = set() # already seen apps to note cyclic dependencies | |
17 self.parsed = {} # instantiated apps | |
18 self.load(config or {}) | |
19 | |
20 def load(self, config, name=None): | |
21 name = name or self.main # load main section by default | |
22 assert name in config, "'%s' not found in config" | |
23 if name in self.parsed: | |
24 return self.parsed[name] | |
25 if name in self.seen: | |
26 raise CircularReferenceError('Circular reference! : %s' % name) | |
27 self.seen.add(name) | |
28 | |
29 # get section | |
30 section = config['name'] | |
31 assert 'path' in section | |
32 | |
33 # load object | |
34 obj = loader.load(section['path']) | |
35 | |
36 # interpolate arguments | |
37 args = section.get('args', None) | |
38 kwargs = section.get('kwargs', None) | |
39 if args: | |
40 args = [self.iterpolate(arg) for arg in args] | |
41 if kwargs: | |
42 kwargs = dict([(key, self.interpolate(value)) | |
43 for key, value in kwargs.items()]) | |
44 | |
45 # if args and kwargs aren't there, you're done! | |
46 | |
47 def interpolate(self, value): | |
48 | |
49 # only interpolate strings | |
50 if not isinstance(value, basestring): | |
51 return value |