Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added Config.names() to return all names in a config (recursively) #24

Merged
merged 1 commit into from
Aug 9, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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