Skip to content

Commit

Permalink
Added Config.names() to return all names in a config (recursively)
Browse files Browse the repository at this point in the history
  • Loading branch information
RobertLuptonTheGood committed Aug 9, 2018
1 parent 943889d commit 38af687
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 2 deletions.
30 changes: 28 additions & 2 deletions python/lsst/pex/config/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,9 @@
from past.builtins import basestring
from past.builtins import unicode

import os
import io
import os
import re
import sys
import math
import copy
Expand Down Expand Up @@ -237,7 +238,7 @@ def _validateValue(self, value):
This is called from __set__
This is not part of the Field API. However, simple derived field types
may benifit from implementing _validateValue
may benefit from implementing _validateValue
"""
if value is None:
return
Expand Down Expand Up @@ -660,6 +661,31 @@ def toDict(self):
dict_[name] = field.toDict(self)
return dict_

def names(self):
"""!Return all the keys in a config recursively
"""
#
# Rather than sort out the recursion all over again use the
# pre-existing saveToStream()
#
with io.StringIO() as strFd:
self.saveToStream(strFd, "config")
contents = strFd.getvalue()
strFd.close()
#
# Pull the names out of the dumped config
#
keys = []
for line in contents.split("\n"):
if re.search(r"^((assert|import)\s+|\s*$|#)", line):
continue

mat = re.search(r"^(?:config\.)?([^=]+)\s*=\s*.*", line)
if mat:
keys.append(mat.group(1))

return keys

def _rename(self, name):
"""!Rename this Config object in its parent config
Expand Down
12 changes: 12 additions & 0 deletions tests/test_Config.py
Original file line number Diff line number Diff line change
Expand Up @@ -418,6 +418,18 @@ def testLoadError(self):
self.assertRaises(SyntaxError, self.simple.loadFromStream, "bork bork bork")
self.assertRaises(NameError, self.simple.loadFromStream, "config.f = bork")

def testNames(self):
"""Check that the names() method returns valid keys
Also check that we have the right number of keys, and as they are
all known to be valid we know that we got them all
"""

names = self.simple.names()
self.assertEqual(len(names), 8)
for name in names:
self.assertTrue(hasattr(self.simple, name))


class TestMemory(lsst.utils.tests.MemoryTestCase):
pass
Expand Down

0 comments on commit 38af687

Please sign in to comment.