Andriy Kornatskyy avatar Andriy Kornatskyy committed 210ed83

Introduced Config class.

Comments (0)

Files changed (1)

src/wheezy/core/config.py

+
+""" ``config`` module.
+"""
+
+DEBUG = False
+
+
+class Config(object):
+    """ Promotes ``options`` dict to attributes. If an option
+        can not be found in ``options`` tries to get it from
+        ``master``. ``master`` must have a requested option
+        otherwise raises error.
+
+        ``master`` can be a module.
+
+        >>> from sys import modules
+        >>> m = modules[Config.__module__]
+        >>> c = Config(master=m)
+        >>> c.DEBUG
+        False
+
+        or an instance of ``dict``.
+
+        >>> c = Config(master={'DEBUG': False})
+        >>> c.DEBUG
+        False
+
+        ``options`` override ``master``.
+
+        >>> c = Config(options={'DEBUG': True}, master=m)
+        >>> c.DEBUG
+        True
+
+        If option is not defined it takes from ``master``.
+
+        >>> c = Config(master=m)
+        >>> c.DEBUG
+        False
+
+        Configs can be nested
+
+        >>> m = Config(dict(B='b'))
+        >>> c = Config(dict(A='a'), master=m)
+        >>> c.B
+        'b'
+
+        if ``options`` is an instance of ``Config`` than use
+        borg pattern to share state.
+
+        >>> options = Config(dict(A='a'))
+        >>> c = Config(options)
+        >>> c.A
+        'a'
+    """
+
+    def __init__(self, options=None, master=None):
+        if isinstance(options, Config):
+            self.__dict__ = options.__dict__
+        else:
+            self.options = options or {}
+            if master:
+                if isinstance(master, dict):
+                    self.get_master = lambda n: master[n]
+                else:
+                    self.get_master = lambda n: getattr(master, n)
+            else:
+                self.get_master = lambda n: None
+
+    def __getattr__(self, name):
+        if name in self.options:
+            val = self.options[name]
+        else:
+            val = self.get_master(name)
+        setattr(self, name, val)
+        return val
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.