changeset 9:ff634cc2e62b

unfinished sketch of an abstract factory
author Jeff Hammel <jhammel@mozilla.com>
date Thu, 26 May 2011 18:14:56 -0700
parents 4d3ea44fd813
children ba2355d57998
files README.txt pyloader/factory.py
diffstat 2 files changed, 55 insertions(+), 1 deletions(-) [+]
line wrap: on
line diff
--- a/README.txt	Wed May 25 09:00:28 2011 -0700
+++ b/README.txt	Thu May 26 18:14:56 2011 -0700
@@ -62,7 +62,10 @@
 
   ``args`` is extended. ``kwargs`` will be overridden.
 
-- wrappers:
+- wrappers: in addition to the override pattern, you can also wrap an
+  object::
+
+   [foo:bar:baz]
 
 In addition, .ini files may include other .ini files.  This allows for
 encapsulation of intent of specific .ini files::
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pyloader/factory.py	Thu May 26 18:14:56 2011 -0700
@@ -0,0 +1,51 @@
+"""
+abstract factories
+"""
+
+import loader
+
+class CircularReferenceError(Exception):
+    """factory has detected a circular reference"""
+
+class PyFactory(object):
+
+    delimeters = ('%(', ')s')
+
+    def __init__(self, config=None, main=''):
+        self.main = main  # main section
+        self.seen = set() # already seen apps to note cyclic dependencies
+        self.parsed = {}  # instantiated apps
+        self.load(config or {})
+
+    def load(self, config, name=None):
+        name = name or self.main # load main section by default
+        assert name in config, "'%s' not found in config"
+        if name in self.parsed:
+            return self.parsed[name]
+        if name in self.seen:
+            raise CircularReferenceError('Circular reference! : %s' % name)
+        self.seen.add(name)
+
+        # get section
+        section = config['name']
+        assert 'path' in section
+
+        # load object
+        obj = loader.load(section['path'])
+
+        # interpolate arguments
+        args = section.get('args', None)
+        kwargs = section.get('kwargs', None)
+        if args:
+            args = [self.iterpolate(arg) for arg in args]
+        if kwargs:
+            kwargs = dict([(key, self.interpolate(value))
+                           for key, value in kwargs.items()])
+        
+        # if args and kwargs aren't there, you're done!
+
+    def interpolate(self, value):
+
+        # only interpolate strings
+        if not isinstance(value, basestring):
+            return value