diff options
author | Picca Frédéric-Emmanuel <picca@debian.org> | 2024-02-05 16:30:07 +0100 |
---|---|---|
committer | Picca Frédéric-Emmanuel <picca@debian.org> | 2024-02-05 16:30:07 +0100 |
commit | 04095a69f18767d222b16fae5b40f2b712cd6f7e (patch) | |
tree | d20abd3ee2f237319443e9dfd7500ad55d29a33d /src/silx/io/configdict.py | |
parent | 3427caf0e96690e56aac6231a91df8f0f7a64fc2 (diff) |
New upstream version 2.0.0+dfsg
Diffstat (limited to 'src/silx/io/configdict.py')
-rw-r--r-- | src/silx/io/configdict.py | 115 |
1 files changed, 54 insertions, 61 deletions
diff --git a/src/silx/io/configdict.py b/src/silx/io/configdict.py index c028211..e2a012e 100644 --- a/src/silx/io/configdict.py +++ b/src/silx/io/configdict.py @@ -1,5 +1,5 @@ # /*########################################################################## -# Copyright (C) 2004-2018 European Synchrotron Radiation Facility +# Copyright (C) 2004-2023 European Synchrotron Radiation Facility # # This file is part of the PyMca X-ray Fluorescence Toolkit developed at # the ESRF by the Software group. @@ -88,17 +88,9 @@ __author__ = ["E. Papillon", "V.A. Sole", "P. Knobel"] __license__ = "MIT" __date__ = "15/09/2016" -from collections import OrderedDict import numpy import re -import sys -if sys.version_info < (3, ): - import ConfigParser as configparser -else: - import configparser - - -string_types = (basestring,) if sys.version_info[0] == 2 else (str,) # noqa +import configparser def _boolean(sstr): @@ -112,9 +104,9 @@ def _boolean(sstr): :raise: ``ValueError`` if ``sstr`` is not a valid string representation of a boolean """ - if sstr.lower() in ['1', 'yes', 'true', 'on']: + if sstr.lower() in ["1", "yes", "true", "on"]: return True - if sstr.lower() in ['0', 'no', 'false', 'off']: + if sstr.lower() in ["0", "no", "false", "off"]: return False msg = "Cannot coerce string '%s' to a boolean value. " % sstr msg += "Valid boolean strings: '1', 'yes', 'true', 'on', " @@ -171,20 +163,19 @@ def _parse_container(sstr): if not sstr: raise ValueError - if sstr.find(',') == -1: + if sstr.find(",") == -1: # it is not a list - if (sstr[0] == '[') and (sstr[-1] == ']'): + if (sstr[0] == "[") and (sstr[-1] == "]"): # this looks like an array try: # try parsing as a 1D array return numpy.array([float(x) for x in sstr[1:-1].split()]) except ValueError: # try parsing as a 2D array - if (sstr[2] == '[') and (sstr[-3] == ']'): - nrows = len(sstr[3:-3].split('] [')) - data = sstr[3:-3].replace('] [', ' ') - data = numpy.array([float(x) for x in - data.split()]) + if (sstr[2] == "[") and (sstr[-3] == "]"): + nrows = len(sstr[3:-3].split("] [")) + data = sstr[3:-3].replace("] [", " ") + data = numpy.array([float(x) for x in data.split()]) data.shape = nrows, -1 return data # not a list and not an array @@ -215,21 +206,22 @@ def _parse_list_line(sstr): # (_parse_simple_types recognizes ^@ as a comma) sstr.replace(r"\,", "^@") # it is a list - if sstr.endswith(','): - if ',' in sstr[:-1]: - return [_parse_simple_types(sstr2.strip()) - for sstr2 in sstr[:-1].split(',')] + if sstr.endswith(","): + if "," in sstr[:-1]: + return [ + _parse_simple_types(sstr2.strip()) for sstr2 in sstr[:-1].split(",") + ] else: return [_parse_simple_types(sstr[:-1].strip())] else: - return [_parse_simple_types(sstr2.strip()) - for sstr2 in sstr.split(',')] + return [_parse_simple_types(sstr2.strip()) for sstr2 in sstr.split(",")] class OptionStr(str): """String class providing typecasting methods to parse values in a :class:`ConfigDict` generated configuration file. """ + def toint(self): """ :return: integer @@ -288,7 +280,7 @@ class OptionStr(str): return _parse_simple_types(self) -class ConfigDict(OrderedDict): +class ConfigDict(dict): """Store configuration parameters as an ordered dictionary. Parameters can be grouped into sections, by storing them as @@ -318,9 +310,10 @@ class ConfigDict(OrderedDict): :param filelist: List of configuration files to be read and added into dict after ``defaultdict`` and ``initdict`` """ + def __init__(self, defaultdict=None, initdict=None, filelist=None): - self.default = defaultdict if defaultdict is not None else OrderedDict() - OrderedDict.__init__(self, self.default) + self.default = defaultdict if defaultdict is not None else {} + super().__init__(self.default) self.filelist = [] if initdict is not None: @@ -329,19 +322,17 @@ class ConfigDict(OrderedDict): self.read(filelist) def reset(self): - """ Revert to default values - """ + """Revert to default values""" self.clear() self.update(self.default) def clear(self): - """ Clear dictionnary - """ - OrderedDict.clear(self) + """Clear dictionnary""" + super().clear() self.filelist = [] def __tolist(self, mylist): - """ If ``mylist` is not a list, encapsulate it in a list and return + """If ``mylist` is not a list, encapsulate it in a list and return it. :param mylist: List to encapsulate @@ -411,10 +402,10 @@ class ConfigDict(OrderedDict): for sect in readsect: ddict = self - for subsectw in sect.split('.'): + for subsectw in sect.split("."): subsect = subsectw.replace("_|_", ".") if not subsect in ddict: - ddict[subsect] = OrderedDict() + ddict[subsect] = {} ddict = ddict[subsect] for opt in cfg.options(sect): ddict[opt] = self.__parse_data(cfg.get(sect, opt)) @@ -431,9 +422,9 @@ class ConfigDict(OrderedDict): return OptionStr(data).tobestguess() def tostring(self): - """Return INI file content generated by :meth:`write` as a string - """ + """Return INI file content generated by :meth:`write` as a string""" import StringIO + tmp = StringIO.StringIO() self.__write(tmp, self) return tmp.getvalue() @@ -469,15 +460,14 @@ class ConfigDict(OrderedDict): the interpolation syntax (https://docs.python.org/3/library/configparser.html#interpolation-of-values). """ - non_str = r'^([0-9]+|[0-9]*\.[0-9]*|none|false|true|on|off|yes|no)$' + non_str = r"^([0-9]+|[0-9]*\.[0-9]*|none|false|true|on|off|yes|no)$" if re.match(non_str, sstr.lower()): sstr = "\\" + sstr # Escape commas sstr = sstr.replace(",", r"\,") - if sys.version_info >= (3, ): - # Escape % characters except in "%%" and "%(" - sstr = re.sub(r'%([^%\(])', r'%%\1', sstr) + # Escape % characters except in "%%" and "%(" + sstr = re.sub(r"%([^%\(])", r"%%\1", sstr) return sstr @@ -492,49 +482,52 @@ class ConfigDict(OrderedDict): dictkey = [] for key in ddict.keys(): - if hasattr(ddict[key], 'keys'): + if hasattr(ddict[key], "keys"): # subsections are added at the end of a section dictkey.append(key) elif isinstance(ddict[key], list): - fp.write('%s = ' % key) + fp.write("%s = " % key) llist = [] - sep = ', ' + sep = ", " for item in ddict[key]: if isinstance(item, list): if len(item) == 1: - if isinstance(item[0], string_types): + if isinstance(item[0], str): self._escape_str(item[0]) - llist.append('%s,' % self._escape_str(item[0])) + llist.append("%s," % self._escape_str(item[0])) else: - llist.append('%s,' % item[0]) + llist.append("%s," % item[0]) else: item2 = [] for val in item: - if isinstance(val, string_types): + if isinstance(val, str): val = self._escape_str(val) item2.append(val) - llist.append(', '.join([str(val) for val in item2])) - sep = '\n\t' - elif isinstance(item, string_types): + llist.append(", ".join([str(val) for val in item2])) + sep = "\n\t" + elif isinstance(item, str): llist.append(self._escape_str(item)) else: llist.append(str(item)) - fp.write('%s\n' % (sep.join(llist))) - elif isinstance(ddict[key], string_types): - fp.write('%s = %s\n' % (key, self._escape_str(ddict[key]))) + fp.write("%s\n" % (sep.join(llist))) + elif isinstance(ddict[key], str): + fp.write("%s = %s\n" % (key, self._escape_str(ddict[key]))) else: if isinstance(ddict[key], numpy.ndarray): - fp.write('%s =' % key + ' [ ' + - ' '.join([str(val) for val in ddict[key]]) + - ' ]\n') + fp.write( + "%s =" % key + + " [ " + + " ".join([str(val) for val in ddict[key]]) + + " ]\n" + ) else: - fp.write('%s = %s\n' % (key, ddict[key])) + fp.write("%s = %s\n" % (key, ddict[key])) for key in dictkey: if secthead is None: newsecthead = key.replace(".", "_|_") else: - newsecthead = '%s.%s' % (secthead, key.replace(".", "_|_")) + newsecthead = "%s.%s" % (secthead, key.replace(".", "_|_")) - fp.write('\n[%s]\n' % newsecthead) + fp.write("\n[%s]\n" % newsecthead) self.__write(fp, ddict[key], newsecthead) |