]> mj.ucw.cz Git - eval.git/blobdiff - t/moe/config.py
Added unfix(), corrected fix()
[eval.git] / t / moe / config.py
index 04e363f1887ef53446392b202a34df97faa00630..e6ce045913797a4ff411ee84357fe543f1ab9a1d 100644 (file)
@@ -55,6 +55,17 @@ class VariableFixedError(ConfigError):
 class CyclicConfigError(ConfigError):
   pass
 
+class ParseProxy(list):
+  """Proxy helper class around values returned by `parse` and `parse_file`, 
+  useful in "with" constructs."""
+  def __init__(self, config, parsed_ops):
+    super(ParseProxy, self).__init__(parsed_ops)  
+    self.config = config
+  def __enter__(self):
+    pass
+  def __exit__(self, etype, value, traceback):
+    self.config.remove(list(self))
+
 
 class ConfigTree(object):
   """
@@ -99,7 +110,14 @@ class ConfigTree(object):
     if isinstance(keys, types.StringTypes):
       keys = [keys]
     for key in keys:
-      self.lookup(key, create=True).fix()
+      self.lookup(key, create=False).fix()
+  
+  def unfix(self, keys):
+    "Unfix value of variable or list of variables. Unfixing undefined variable raises `UndefinedError`."
+    if isinstance(keys, types.StringTypes):
+      keys = [keys]
+    for key in keys:
+      self.lookup(key, create=False).unfix()
 
   def remove(self, parsed):
     """Given a list [(varname, `Operation`)] as returned by `parse` or `parse_file`, 
@@ -110,20 +128,29 @@ class ConfigTree(object):
       v = self.lookup(vname, create = True)
       v.remove_operation(o)
 
-  def parse(self, s, source=None, level=0):
-    """Parse `s` (stream/string) into the tree, see `moe.confparser.ConfigParser` for details.
-    Returns list of parset operations: [(varname, `Operation`)]"""
+  def parse(self, s, source=None, level=0, proxy=True):
+    """Parse `s` (stream/string) into the tree, see `moe.config_parser.ConfigParser` for details.
+    Returns list of parset operations: [(varname, `Operation`)].
+    By default returns a proxy list-like object that can be used in "with" constructs:
+      
+      with config.parse("TEST='1'"):
+       print config['TEST']
+       raise StupidError
+    """
     import moe.config_parser
     p = moe.config_parser.ConfigParser(s, self, source=source, level=level)
-    return p.parse()
+    l = p.parse()
+    if not proxy:
+      return l
+    return ParseProxy(self, l)
 
-  def parse_file(self, filename, desc=None, level=0):
-    """Parse an utf-8 file into the tree, see `moe.confparser.ConfigParser` for details
+  def parse_file(self, filename, desc=None, level=0, proxy=True):
+    """Parse an utf-8 file into the tree using func:`parse`
     Names the source "`filename` <`desc`>". """
     with open(filename, 'rt') as f:
       if desc: 
        filename += " <" + desc + ">" 
-      return self.parse(f, source=filename, level=level)
+      return self.parse(f, source=filename, level=level, proxy=proxy)
 
 
 class ConfigElem(object):