repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_documentation_string
stringlengths
1
47.2k
func_code_url
stringlengths
85
339
ssato/python-anyconfig
src/anyconfig/processors.py
Processors.register
def register(self, *pclss): """ :param pclss: A list of :class:`Processor` or its children classes """ for pcls in pclss: if pcls.cid() not in self._processors: self._processors[pcls.cid()] = pcls
python
def register(self, *pclss): """ :param pclss: A list of :class:`Processor` or its children classes """ for pcls in pclss: if pcls.cid() not in self._processors: self._processors[pcls.cid()] = pcls
:param pclss: A list of :class:`Processor` or its children classes
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/processors.py#L243-L249
ssato/python-anyconfig
src/anyconfig/processors.py
Processors.list
def list(self, sort=False): """ :param sort: Result will be sorted if it's True :return: A list of :class:`Processor` or its children classes """ prs = self._processors.values() if sort: return sorted(prs, key=operator.methodcaller("cid")) return prs
python
def list(self, sort=False): """ :param sort: Result will be sorted if it's True :return: A list of :class:`Processor` or its children classes """ prs = self._processors.values() if sort: return sorted(prs, key=operator.methodcaller("cid")) return prs
:param sort: Result will be sorted if it's True :return: A list of :class:`Processor` or its children classes
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/processors.py#L257-L266
ssato/python-anyconfig
src/anyconfig/processors.py
Processors.list_by_cid
def list_by_cid(self): """ :return: A list of :class:`Processor` or its children classes grouped by each cid, [(cid, [:class:`Processor`)]] """ prs = self._processors return sorted(((cid, [prs[cid]]) for cid in sorted(prs.keys())), key=operator.itemgetter(0))
python
def list_by_cid(self): """ :return: A list of :class:`Processor` or its children classes grouped by each cid, [(cid, [:class:`Processor`)]] """ prs = self._processors return sorted(((cid, [prs[cid]]) for cid in sorted(prs.keys())), key=operator.itemgetter(0))
:return: A list of :class:`Processor` or its children classes grouped by each cid, [(cid, [:class:`Processor`)]]
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/processors.py#L268-L276
ssato/python-anyconfig
src/anyconfig/processors.py
Processors.list_by_x
def list_by_x(self, item=None): """ :param item: Grouping key, one of "cid", "type" and "extensions" :return: A list of :class:`Processor` or its children classes grouped by given 'item', [(cid, [:class:`Processor`)]] by default """ prs = self._processors if item is None or item == "cid": # Default. res = [(cid, [prs[cid]]) for cid in sorted(prs.keys())] elif item in ("type", "extensions"): res = list_by_x(prs.values(), item) else: raise ValueError("keyword argument 'item' must be one of " "None, 'cid', 'type' and 'extensions' " "but it was '%s'" % item) return res
python
def list_by_x(self, item=None): """ :param item: Grouping key, one of "cid", "type" and "extensions" :return: A list of :class:`Processor` or its children classes grouped by given 'item', [(cid, [:class:`Processor`)]] by default """ prs = self._processors if item is None or item == "cid": # Default. res = [(cid, [prs[cid]]) for cid in sorted(prs.keys())] elif item in ("type", "extensions"): res = list_by_x(prs.values(), item) else: raise ValueError("keyword argument 'item' must be one of " "None, 'cid', 'type' and 'extensions' " "but it was '%s'" % item) return res
:param item: Grouping key, one of "cid", "type" and "extensions" :return: A list of :class:`Processor` or its children classes grouped by given 'item', [(cid, [:class:`Processor`)]] by default
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/processors.py#L286-L304
ssato/python-anyconfig
src/anyconfig/processors.py
Processors.list_x
def list_x(self, key=None): """ :param key: Which of key to return from "cid", "type", and "extention" :return: A list of x 'key' """ if key in ("cid", "type"): return sorted(set(operator.methodcaller(key)(p) for p in self._processors.values())) if key == "extension": return sorted(k for k, _v in self.list_by_x("extensions")) raise ValueError("keyword argument 'key' must be one of " "None, 'cid', 'type' and 'extension' " "but it was '%s'" % key)
python
def list_x(self, key=None): """ :param key: Which of key to return from "cid", "type", and "extention" :return: A list of x 'key' """ if key in ("cid", "type"): return sorted(set(operator.methodcaller(key)(p) for p in self._processors.values())) if key == "extension": return sorted(k for k, _v in self.list_by_x("extensions")) raise ValueError("keyword argument 'key' must be one of " "None, 'cid', 'type' and 'extension' " "but it was '%s'" % key)
:param key: Which of key to return from "cid", "type", and "extention" :return: A list of x 'key'
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/processors.py#L306-L319
ssato/python-anyconfig
src/anyconfig/processors.py
Processors.findall
def findall(self, obj, forced_type=None, cls=anyconfig.models.processor.Processor): """ :param obj: a file path, file, file-like object, pathlib.Path object or an 'anyconfig.globals.IOInfo' (namedtuple) object :param forced_type: Forced processor type to find :param cls: A class object to compare with 'ptype' :return: A list of instances of processor classes to process 'obj' :raises: ValueError, UnknownProcessorTypeError, UnknownFileTypeError """ return [p() for p in findall(obj, self.list(), forced_type=forced_type, cls=cls)]
python
def findall(self, obj, forced_type=None, cls=anyconfig.models.processor.Processor): """ :param obj: a file path, file, file-like object, pathlib.Path object or an 'anyconfig.globals.IOInfo' (namedtuple) object :param forced_type: Forced processor type to find :param cls: A class object to compare with 'ptype' :return: A list of instances of processor classes to process 'obj' :raises: ValueError, UnknownProcessorTypeError, UnknownFileTypeError """ return [p() for p in findall(obj, self.list(), forced_type=forced_type, cls=cls)]
:param obj: a file path, file, file-like object, pathlib.Path object or an 'anyconfig.globals.IOInfo' (namedtuple) object :param forced_type: Forced processor type to find :param cls: A class object to compare with 'ptype' :return: A list of instances of processor classes to process 'obj' :raises: ValueError, UnknownProcessorTypeError, UnknownFileTypeError
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/processors.py#L321-L334
ssato/python-anyconfig
src/anyconfig/processors.py
Processors.find
def find(self, obj, forced_type=None, cls=anyconfig.models.processor.Processor): """ :param obj: a file path, file, file-like object, pathlib.Path object or an 'anyconfig.globals.IOInfo' (namedtuple) object :param forced_type: Forced processor type to find :param cls: A class object to compare with 'ptype' :return: an instance of processor class to process 'obj' :raises: ValueError, UnknownProcessorTypeError, UnknownFileTypeError """ return find(obj, self.list(), forced_type=forced_type, cls=cls)
python
def find(self, obj, forced_type=None, cls=anyconfig.models.processor.Processor): """ :param obj: a file path, file, file-like object, pathlib.Path object or an 'anyconfig.globals.IOInfo' (namedtuple) object :param forced_type: Forced processor type to find :param cls: A class object to compare with 'ptype' :return: an instance of processor class to process 'obj' :raises: ValueError, UnknownProcessorTypeError, UnknownFileTypeError """ return find(obj, self.list(), forced_type=forced_type, cls=cls)
:param obj: a file path, file, file-like object, pathlib.Path object or an 'anyconfig.globals.IOInfo' (namedtuple) object :param forced_type: Forced processor type to find :param cls: A class object to compare with 'ptype' :return: an instance of processor class to process 'obj' :raises: ValueError, UnknownProcessorTypeError, UnknownFileTypeError
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/processors.py#L336-L348
ssato/python-anyconfig
src/anyconfig/backend/yaml/ruamel_yaml.py
yml_fnc
def yml_fnc(fname, *args, **options): """ :param fname: "load" or "dump", not checked but it should be OK. see also :func:`yml_load` and :func:`yml_dump` :param args: [stream] for load or [cnf, stream] for dump :param options: keyword args may contain "ac_safe" to load/dump safely """ options = common.filter_from_options("ac_dict", options) if "ac_safe" in options: options["typ"] = "safe" # Override it. iopts = anyconfig.utils.filter_options(_YAML_INIT_KWARGS, options) oopts = anyconfig.utils.filter_options(_YAML_INSTANCE_MEMBERS, options) yml = ryaml.YAML(**iopts) for attr, val in oopts.items(): setattr(yml, attr, val) # e.g. yml.preserve_quotes = True return getattr(yml, fname)(*args)
python
def yml_fnc(fname, *args, **options): """ :param fname: "load" or "dump", not checked but it should be OK. see also :func:`yml_load` and :func:`yml_dump` :param args: [stream] for load or [cnf, stream] for dump :param options: keyword args may contain "ac_safe" to load/dump safely """ options = common.filter_from_options("ac_dict", options) if "ac_safe" in options: options["typ"] = "safe" # Override it. iopts = anyconfig.utils.filter_options(_YAML_INIT_KWARGS, options) oopts = anyconfig.utils.filter_options(_YAML_INSTANCE_MEMBERS, options) yml = ryaml.YAML(**iopts) for attr, val in oopts.items(): setattr(yml, attr, val) # e.g. yml.preserve_quotes = True return getattr(yml, fname)(*args)
:param fname: "load" or "dump", not checked but it should be OK. see also :func:`yml_load` and :func:`yml_dump` :param args: [stream] for load or [cnf, stream] for dump :param options: keyword args may contain "ac_safe" to load/dump safely
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/yaml/ruamel_yaml.py#L73-L93
ssato/python-anyconfig
src/anyconfig/backend/yaml/ruamel_yaml.py
yml_load
def yml_load(stream, container, **options): """.. seealso:: :func:`anyconfig.backend.yaml.pyyaml.yml_load` """ ret = yml_fnc("load", stream, **options) if ret is None: return container() return ret
python
def yml_load(stream, container, **options): """.. seealso:: :func:`anyconfig.backend.yaml.pyyaml.yml_load` """ ret = yml_fnc("load", stream, **options) if ret is None: return container() return ret
.. seealso:: :func:`anyconfig.backend.yaml.pyyaml.yml_load`
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/yaml/ruamel_yaml.py#L96-L103
ssato/python-anyconfig
src/anyconfig/backend/xml.py
_iterparse
def _iterparse(xmlfile): """ Avoid bug in python 3.{2,3}. See http://bugs.python.org/issue9257. :param xmlfile: XML file or file-like object """ try: return ET.iterparse(xmlfile, events=("start-ns", )) except TypeError: return ET.iterparse(xmlfile, events=(b"start-ns", ))
python
def _iterparse(xmlfile): """ Avoid bug in python 3.{2,3}. See http://bugs.python.org/issue9257. :param xmlfile: XML file or file-like object """ try: return ET.iterparse(xmlfile, events=("start-ns", )) except TypeError: return ET.iterparse(xmlfile, events=(b"start-ns", ))
Avoid bug in python 3.{2,3}. See http://bugs.python.org/issue9257. :param xmlfile: XML file or file-like object
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/xml.py#L82-L91
ssato/python-anyconfig
src/anyconfig/backend/xml.py
_tweak_ns
def _tweak_ns(tag, **options): """ :param tag: XML tag element :param nspaces: A namespaces dict, {uri: prefix} :param options: Extra keyword options may contain 'nspaces' keyword option provide a namespace dict, {uri: prefix} >>> _tweak_ns("a", nspaces={}) 'a' >>> _tweak_ns("a", nspaces={"http://example.com/ns/val/": "val"}) 'a' >>> _tweak_ns("{http://example.com/ns/val/}a", ... nspaces={"http://example.com/ns/val/": "val"}) 'val:a' """ nspaces = options.get("nspaces", None) if nspaces is not None: matched = _ET_NS_RE.match(tag) if matched: (uri, tag) = matched.groups() prefix = nspaces.get(uri, False) if prefix: return "%s:%s" % (prefix, tag) return tag
python
def _tweak_ns(tag, **options): """ :param tag: XML tag element :param nspaces: A namespaces dict, {uri: prefix} :param options: Extra keyword options may contain 'nspaces' keyword option provide a namespace dict, {uri: prefix} >>> _tweak_ns("a", nspaces={}) 'a' >>> _tweak_ns("a", nspaces={"http://example.com/ns/val/": "val"}) 'a' >>> _tweak_ns("{http://example.com/ns/val/}a", ... nspaces={"http://example.com/ns/val/": "val"}) 'val:a' """ nspaces = options.get("nspaces", None) if nspaces is not None: matched = _ET_NS_RE.match(tag) if matched: (uri, tag) = matched.groups() prefix = nspaces.get(uri, False) if prefix: return "%s:%s" % (prefix, tag) return tag
:param tag: XML tag element :param nspaces: A namespaces dict, {uri: prefix} :param options: Extra keyword options may contain 'nspaces' keyword option provide a namespace dict, {uri: prefix} >>> _tweak_ns("a", nspaces={}) 'a' >>> _tweak_ns("a", nspaces={"http://example.com/ns/val/": "val"}) 'a' >>> _tweak_ns("{http://example.com/ns/val/}a", ... nspaces={"http://example.com/ns/val/": "val"}) 'val:a'
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/xml.py#L110-L134
ssato/python-anyconfig
src/anyconfig/backend/xml.py
_dicts_have_unique_keys
def _dicts_have_unique_keys(dics): """ :param dics: [<dict or dict-like object>], must not be [] or [{...}] :return: True if all keys of each dict of 'dics' are unique # Enable the followings if to allow dics is [], [{...}]: # >>> all(_dicts_have_unique_keys([d]) for [d] # ... in ({}, {'a': 0}, {'a': 1, 'b': 0})) # True # >>> _dicts_have_unique_keys([{}, {'a': 1}, {'b': 2, 'c': 0}]) # True >>> _dicts_have_unique_keys([{}, {'a': 1}, {'a': 2}]) False >>> _dicts_have_unique_keys([{}, {'a': 1}, {'b': 2}, {'b': 3, 'c': 0}]) False >>> _dicts_have_unique_keys([{}, {}]) True """ key_itr = anyconfig.compat.from_iterable(d.keys() for d in dics) return len(set(key_itr)) == sum(len(d) for d in dics)
python
def _dicts_have_unique_keys(dics): """ :param dics: [<dict or dict-like object>], must not be [] or [{...}] :return: True if all keys of each dict of 'dics' are unique # Enable the followings if to allow dics is [], [{...}]: # >>> all(_dicts_have_unique_keys([d]) for [d] # ... in ({}, {'a': 0}, {'a': 1, 'b': 0})) # True # >>> _dicts_have_unique_keys([{}, {'a': 1}, {'b': 2, 'c': 0}]) # True >>> _dicts_have_unique_keys([{}, {'a': 1}, {'a': 2}]) False >>> _dicts_have_unique_keys([{}, {'a': 1}, {'b': 2}, {'b': 3, 'c': 0}]) False >>> _dicts_have_unique_keys([{}, {}]) True """ key_itr = anyconfig.compat.from_iterable(d.keys() for d in dics) return len(set(key_itr)) == sum(len(d) for d in dics)
:param dics: [<dict or dict-like object>], must not be [] or [{...}] :return: True if all keys of each dict of 'dics' are unique # Enable the followings if to allow dics is [], [{...}]: # >>> all(_dicts_have_unique_keys([d]) for [d] # ... in ({}, {'a': 0}, {'a': 1, 'b': 0})) # True # >>> _dicts_have_unique_keys([{}, {'a': 1}, {'b': 2, 'c': 0}]) # True >>> _dicts_have_unique_keys([{}, {'a': 1}, {'a': 2}]) False >>> _dicts_have_unique_keys([{}, {'a': 1}, {'b': 2}, {'b': 3, 'c': 0}]) False >>> _dicts_have_unique_keys([{}, {}]) True
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/xml.py#L137-L157
ssato/python-anyconfig
src/anyconfig/backend/xml.py
_merge_dicts
def _merge_dicts(dics, container=dict): """ :param dics: [<dict/-like object must not have same keys each other>] :param container: callble to make a container object :return: <container> object >>> _merge_dicts(({}, )) {} >>> _merge_dicts(({'a': 1}, )) {'a': 1} >>> sorted(kv for kv in _merge_dicts(({'a': 1}, {'b': 2})).items()) [('a', 1), ('b', 2)] """ dic_itr = anyconfig.compat.from_iterable(d.items() for d in dics) return container(anyconfig.compat.OrderedDict(dic_itr))
python
def _merge_dicts(dics, container=dict): """ :param dics: [<dict/-like object must not have same keys each other>] :param container: callble to make a container object :return: <container> object >>> _merge_dicts(({}, )) {} >>> _merge_dicts(({'a': 1}, )) {'a': 1} >>> sorted(kv for kv in _merge_dicts(({'a': 1}, {'b': 2})).items()) [('a', 1), ('b', 2)] """ dic_itr = anyconfig.compat.from_iterable(d.items() for d in dics) return container(anyconfig.compat.OrderedDict(dic_itr))
:param dics: [<dict/-like object must not have same keys each other>] :param container: callble to make a container object :return: <container> object >>> _merge_dicts(({}, )) {} >>> _merge_dicts(({'a': 1}, )) {'a': 1} >>> sorted(kv for kv in _merge_dicts(({'a': 1}, {'b': 2})).items()) [('a', 1), ('b', 2)]
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/xml.py#L160-L174
ssato/python-anyconfig
src/anyconfig/backend/xml.py
_parse_text
def _parse_text(val, **options): """ :return: Parsed value or value itself depends on 'ac_parse_value' """ if val and options.get("ac_parse_value", False): return anyconfig.parser.parse_single(val) return val
python
def _parse_text(val, **options): """ :return: Parsed value or value itself depends on 'ac_parse_value' """ if val and options.get("ac_parse_value", False): return anyconfig.parser.parse_single(val) return val
:return: Parsed value or value itself depends on 'ac_parse_value'
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/xml.py#L177-L184
ssato/python-anyconfig
src/anyconfig/backend/xml.py
_process_elem_text
def _process_elem_text(elem, dic, subdic, text="@text", **options): """ :param elem: ET Element object which has elem.text :param dic: <container> (dict[-like]) object converted from elem :param subdic: Sub <container> object converted from elem :param options: Keyword options, see the description of :func:`elem_to_container` for more details. :return: None but updating elem.text, dic and subdic as side effects """ elem.text = elem.text.strip() if elem.text: etext = _parse_text(elem.text, **options) if len(elem) or elem.attrib: subdic[text] = etext else: dic[elem.tag] = etext
python
def _process_elem_text(elem, dic, subdic, text="@text", **options): """ :param elem: ET Element object which has elem.text :param dic: <container> (dict[-like]) object converted from elem :param subdic: Sub <container> object converted from elem :param options: Keyword options, see the description of :func:`elem_to_container` for more details. :return: None but updating elem.text, dic and subdic as side effects """ elem.text = elem.text.strip() if elem.text: etext = _parse_text(elem.text, **options) if len(elem) or elem.attrib: subdic[text] = etext else: dic[elem.tag] = etext
:param elem: ET Element object which has elem.text :param dic: <container> (dict[-like]) object converted from elem :param subdic: Sub <container> object converted from elem :param options: Keyword options, see the description of :func:`elem_to_container` for more details. :return: None but updating elem.text, dic and subdic as side effects
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/xml.py#L187-L204
ssato/python-anyconfig
src/anyconfig/backend/xml.py
_parse_attrs
def _parse_attrs(elem, container=dict, **options): """ :param elem: ET Element object has attributes (elem.attrib) :param container: callble to make a container object :return: Parsed value or value itself depends on 'ac_parse_value' """ adic = dict((_tweak_ns(a, **options), v) for a, v in elem.attrib.items()) if options.get("ac_parse_value", False): return container(dict((k, anyconfig.parser.parse_single(v)) for k, v in adic.items())) return container(adic)
python
def _parse_attrs(elem, container=dict, **options): """ :param elem: ET Element object has attributes (elem.attrib) :param container: callble to make a container object :return: Parsed value or value itself depends on 'ac_parse_value' """ adic = dict((_tweak_ns(a, **options), v) for a, v in elem.attrib.items()) if options.get("ac_parse_value", False): return container(dict((k, anyconfig.parser.parse_single(v)) for k, v in adic.items())) return container(adic)
:param elem: ET Element object has attributes (elem.attrib) :param container: callble to make a container object :return: Parsed value or value itself depends on 'ac_parse_value'
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/xml.py#L207-L218
ssato/python-anyconfig
src/anyconfig/backend/xml.py
_process_elem_attrs
def _process_elem_attrs(elem, dic, subdic, container=dict, attrs="@attrs", **options): """ :param elem: ET Element object or None :param dic: <container> (dict[-like]) object converted from elem :param subdic: Sub <container> object converted from elem :param options: Keyword options, see the description of :func:`elem_to_container` for more details. :return: None but updating dic and subdic as side effects """ adic = _parse_attrs(elem, container=container, **options) if not elem.text and not len(elem) and options.get("merge_attrs"): dic[elem.tag] = adic else: subdic[attrs] = adic
python
def _process_elem_attrs(elem, dic, subdic, container=dict, attrs="@attrs", **options): """ :param elem: ET Element object or None :param dic: <container> (dict[-like]) object converted from elem :param subdic: Sub <container> object converted from elem :param options: Keyword options, see the description of :func:`elem_to_container` for more details. :return: None but updating dic and subdic as side effects """ adic = _parse_attrs(elem, container=container, **options) if not elem.text and not len(elem) and options.get("merge_attrs"): dic[elem.tag] = adic else: subdic[attrs] = adic
:param elem: ET Element object or None :param dic: <container> (dict[-like]) object converted from elem :param subdic: Sub <container> object converted from elem :param options: Keyword options, see the description of :func:`elem_to_container` for more details. :return: None but updating dic and subdic as side effects
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/xml.py#L221-L237
ssato/python-anyconfig
src/anyconfig/backend/xml.py
_process_children_elems
def _process_children_elems(elem, dic, subdic, container=dict, children="@children", **options): """ :param elem: ET Element object or None :param dic: <container> (dict[-like]) object converted from elem :param subdic: Sub <container> object converted from elem :param container: callble to make a container object :param children: Tag for children nodes :param options: Keyword options, see the description of :func:`elem_to_container` for more details. :return: None but updating dic and subdic as side effects """ cdics = [elem_to_container(c, container=container, **options) for c in elem] merge_attrs = options.get("merge_attrs", False) sdics = [container(elem.attrib) if merge_attrs else subdic] + cdics if _dicts_have_unique_keys(sdics): # ex. <a><b>1</b><c>c</c></a> dic[elem.tag] = _merge_dicts(sdics, container) elif not subdic: # There are no attrs nor text and only these children. dic[elem.tag] = cdics else: subdic[children] = cdics
python
def _process_children_elems(elem, dic, subdic, container=dict, children="@children", **options): """ :param elem: ET Element object or None :param dic: <container> (dict[-like]) object converted from elem :param subdic: Sub <container> object converted from elem :param container: callble to make a container object :param children: Tag for children nodes :param options: Keyword options, see the description of :func:`elem_to_container` for more details. :return: None but updating dic and subdic as side effects """ cdics = [elem_to_container(c, container=container, **options) for c in elem] merge_attrs = options.get("merge_attrs", False) sdics = [container(elem.attrib) if merge_attrs else subdic] + cdics if _dicts_have_unique_keys(sdics): # ex. <a><b>1</b><c>c</c></a> dic[elem.tag] = _merge_dicts(sdics, container) elif not subdic: # There are no attrs nor text and only these children. dic[elem.tag] = cdics else: subdic[children] = cdics
:param elem: ET Element object or None :param dic: <container> (dict[-like]) object converted from elem :param subdic: Sub <container> object converted from elem :param container: callble to make a container object :param children: Tag for children nodes :param options: Keyword options, see the description of :func:`elem_to_container` for more details. :return: None but updating dic and subdic as side effects
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/xml.py#L240-L264
ssato/python-anyconfig
src/anyconfig/backend/xml.py
elem_to_container
def elem_to_container(elem, container=dict, **options): """ Convert XML ElementTree Element to a collection of container objects. Elements are transformed to a node under special tagged nodes, attrs, text and children, to store the type of these elements basically, however, in some special cases like the followings, these nodes are attached to the parent node directly for later convenience. - There is only text element - There are only children elements each has unique keys among all :param elem: ET Element object or None :param container: callble to make a container object :param options: Keyword options - nspaces: A namespaces dict, {uri: prefix} or None - attrs, text, children: Tags for special nodes to keep XML info - merge_attrs: Merge attributes and mix with children nodes, and the information of attributes are lost after its transformation. """ dic = container() if elem is None: return dic elem.tag = _tweak_ns(elem.tag, **options) # {ns}tag -> ns_prefix:tag subdic = dic[elem.tag] = container() options["container"] = container if elem.text: _process_elem_text(elem, dic, subdic, **options) if elem.attrib: _process_elem_attrs(elem, dic, subdic, **options) if len(elem): _process_children_elems(elem, dic, subdic, **options) elif not elem.text and not elem.attrib: # ex. <tag/>. dic[elem.tag] = None return dic
python
def elem_to_container(elem, container=dict, **options): """ Convert XML ElementTree Element to a collection of container objects. Elements are transformed to a node under special tagged nodes, attrs, text and children, to store the type of these elements basically, however, in some special cases like the followings, these nodes are attached to the parent node directly for later convenience. - There is only text element - There are only children elements each has unique keys among all :param elem: ET Element object or None :param container: callble to make a container object :param options: Keyword options - nspaces: A namespaces dict, {uri: prefix} or None - attrs, text, children: Tags for special nodes to keep XML info - merge_attrs: Merge attributes and mix with children nodes, and the information of attributes are lost after its transformation. """ dic = container() if elem is None: return dic elem.tag = _tweak_ns(elem.tag, **options) # {ns}tag -> ns_prefix:tag subdic = dic[elem.tag] = container() options["container"] = container if elem.text: _process_elem_text(elem, dic, subdic, **options) if elem.attrib: _process_elem_attrs(elem, dic, subdic, **options) if len(elem): _process_children_elems(elem, dic, subdic, **options) elif not elem.text and not elem.attrib: # ex. <tag/>. dic[elem.tag] = None return dic
Convert XML ElementTree Element to a collection of container objects. Elements are transformed to a node under special tagged nodes, attrs, text and children, to store the type of these elements basically, however, in some special cases like the followings, these nodes are attached to the parent node directly for later convenience. - There is only text element - There are only children elements each has unique keys among all :param elem: ET Element object or None :param container: callble to make a container object :param options: Keyword options - nspaces: A namespaces dict, {uri: prefix} or None - attrs, text, children: Tags for special nodes to keep XML info - merge_attrs: Merge attributes and mix with children nodes, and the information of attributes are lost after its transformation.
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/xml.py#L267-L307
ssato/python-anyconfig
src/anyconfig/backend/xml.py
_complement_tag_options
def _complement_tag_options(options): """ :param options: Keyword options :: dict >>> ref = _TAGS.copy() >>> ref["text"] = "#text" >>> opts = _complement_tag_options({"tags": {"text": ref["text"]}}) >>> del opts["tags"] # To simplify comparison. >>> sorted(opts.items()) [('attrs', '@attrs'), ('children', '@children'), ('text', '#text')] """ if not all(nt in options for nt in _TAGS): tags = options.get("tags", {}) for ntype, tag in _TAGS.items(): options[ntype] = tags.get(ntype, tag) return options
python
def _complement_tag_options(options): """ :param options: Keyword options :: dict >>> ref = _TAGS.copy() >>> ref["text"] = "#text" >>> opts = _complement_tag_options({"tags": {"text": ref["text"]}}) >>> del opts["tags"] # To simplify comparison. >>> sorted(opts.items()) [('attrs', '@attrs'), ('children', '@children'), ('text', '#text')] """ if not all(nt in options for nt in _TAGS): tags = options.get("tags", {}) for ntype, tag in _TAGS.items(): options[ntype] = tags.get(ntype, tag) return options
:param options: Keyword options :: dict >>> ref = _TAGS.copy() >>> ref["text"] = "#text" >>> opts = _complement_tag_options({"tags": {"text": ref["text"]}}) >>> del opts["tags"] # To simplify comparison. >>> sorted(opts.items()) [('attrs', '@attrs'), ('children', '@children'), ('text', '#text')]
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/xml.py#L310-L326
ssato/python-anyconfig
src/anyconfig/backend/xml.py
root_to_container
def root_to_container(root, container=dict, nspaces=None, **options): """ Convert XML ElementTree Root Element to a collection of container objects. :param root: etree root object or None :param container: callble to make a container object :param nspaces: A namespaces dict, {uri: prefix} or None :param options: Keyword options, - tags: Dict of tags for special nodes to keep XML info, attributes, text and children nodes, e.g. {"attrs": "@attrs", "text": "#text"} """ tree = container() if root is None: return tree if nspaces is not None: for uri, prefix in nspaces.items(): root.attrib["xmlns:" + prefix if prefix else "xmlns"] = uri return elem_to_container(root, container=container, nspaces=nspaces, **_complement_tag_options(options))
python
def root_to_container(root, container=dict, nspaces=None, **options): """ Convert XML ElementTree Root Element to a collection of container objects. :param root: etree root object or None :param container: callble to make a container object :param nspaces: A namespaces dict, {uri: prefix} or None :param options: Keyword options, - tags: Dict of tags for special nodes to keep XML info, attributes, text and children nodes, e.g. {"attrs": "@attrs", "text": "#text"} """ tree = container() if root is None: return tree if nspaces is not None: for uri, prefix in nspaces.items(): root.attrib["xmlns:" + prefix if prefix else "xmlns"] = uri return elem_to_container(root, container=container, nspaces=nspaces, **_complement_tag_options(options))
Convert XML ElementTree Root Element to a collection of container objects. :param root: etree root object or None :param container: callble to make a container object :param nspaces: A namespaces dict, {uri: prefix} or None :param options: Keyword options, - tags: Dict of tags for special nodes to keep XML info, attributes, text and children nodes, e.g. {"attrs": "@attrs", "text": "#text"}
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/xml.py#L329-L350
ssato/python-anyconfig
src/anyconfig/backend/xml.py
_elem_set_attrs
def _elem_set_attrs(obj, parent, to_str): """ :param obj: Container instance gives attributes of XML Element :param parent: XML ElementTree parent node object :param to_str: Callable to convert value to string or None :param options: Keyword options, see :func:`container_to_etree` :return: None but parent will be modified """ for attr, val in anyconfig.compat.iteritems(obj): parent.set(attr, to_str(val))
python
def _elem_set_attrs(obj, parent, to_str): """ :param obj: Container instance gives attributes of XML Element :param parent: XML ElementTree parent node object :param to_str: Callable to convert value to string or None :param options: Keyword options, see :func:`container_to_etree` :return: None but parent will be modified """ for attr, val in anyconfig.compat.iteritems(obj): parent.set(attr, to_str(val))
:param obj: Container instance gives attributes of XML Element :param parent: XML ElementTree parent node object :param to_str: Callable to convert value to string or None :param options: Keyword options, see :func:`container_to_etree` :return: None but parent will be modified
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/xml.py#L361-L371
ssato/python-anyconfig
src/anyconfig/backend/xml.py
_elem_from_descendants
def _elem_from_descendants(children_nodes, **options): """ :param children_nodes: A list of child dict objects :param options: Keyword options, see :func:`container_to_etree` """ for child in children_nodes: # child should be a dict-like object. for ckey, cval in anyconfig.compat.iteritems(child): celem = ET.Element(ckey) container_to_etree(cval, parent=celem, **options) yield celem
python
def _elem_from_descendants(children_nodes, **options): """ :param children_nodes: A list of child dict objects :param options: Keyword options, see :func:`container_to_etree` """ for child in children_nodes: # child should be a dict-like object. for ckey, cval in anyconfig.compat.iteritems(child): celem = ET.Element(ckey) container_to_etree(cval, parent=celem, **options) yield celem
:param children_nodes: A list of child dict objects :param options: Keyword options, see :func:`container_to_etree`
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/xml.py#L374-L383
ssato/python-anyconfig
src/anyconfig/backend/xml.py
_get_or_update_parent
def _get_or_update_parent(key, val, to_str, parent=None, **options): """ :param key: Key of current child (dict{,-like} object) :param val: Value of current child (dict{,-like} object or [dict{,...}]) :param to_str: Callable to convert value to string :param parent: XML ElementTree parent node object or None :param options: Keyword options, see :func:`container_to_etree` """ elem = ET.Element(key) vals = val if anyconfig.utils.is_iterable(val) else [val] for val_ in vals: container_to_etree(val_, parent=elem, to_str=to_str, **options) if parent is None: # 'elem' is the top level etree. return elem parent.append(elem) return parent
python
def _get_or_update_parent(key, val, to_str, parent=None, **options): """ :param key: Key of current child (dict{,-like} object) :param val: Value of current child (dict{,-like} object or [dict{,...}]) :param to_str: Callable to convert value to string :param parent: XML ElementTree parent node object or None :param options: Keyword options, see :func:`container_to_etree` """ elem = ET.Element(key) vals = val if anyconfig.utils.is_iterable(val) else [val] for val_ in vals: container_to_etree(val_, parent=elem, to_str=to_str, **options) if parent is None: # 'elem' is the top level etree. return elem parent.append(elem) return parent
:param key: Key of current child (dict{,-like} object) :param val: Value of current child (dict{,-like} object or [dict{,...}]) :param to_str: Callable to convert value to string :param parent: XML ElementTree parent node object or None :param options: Keyword options, see :func:`container_to_etree`
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/xml.py#L386-L404
ssato/python-anyconfig
src/anyconfig/backend/xml.py
container_to_etree
def container_to_etree(obj, parent=None, to_str=None, **options): """ Convert a dict-like object to XML ElementTree. :param obj: Container instance to convert to :param parent: XML ElementTree parent node object or None :param to_str: Callable to convert value to string or None :param options: Keyword options, - tags: Dict of tags for special nodes to keep XML info, attributes, text and children nodes, e.g. {"attrs": "@attrs", "text": "#text"} """ if to_str is None: to_str = _to_str_fn(**options) if not anyconfig.utils.is_dict_like(obj): if parent is not None and obj: parent.text = to_str(obj) # Parent is a leaf text node. return parent # All attributes and text should be set already. options = _complement_tag_options(options) (attrs, text, children) = operator.itemgetter(*_ATC)(options) for key, val in anyconfig.compat.iteritems(obj): if key == attrs: _elem_set_attrs(val, parent, to_str) elif key == text: parent.text = to_str(val) elif key == children: for celem in _elem_from_descendants(val, **options): parent.append(celem) else: parent = _get_or_update_parent(key, val, to_str, parent=parent, **options) return ET.ElementTree(parent)
python
def container_to_etree(obj, parent=None, to_str=None, **options): """ Convert a dict-like object to XML ElementTree. :param obj: Container instance to convert to :param parent: XML ElementTree parent node object or None :param to_str: Callable to convert value to string or None :param options: Keyword options, - tags: Dict of tags for special nodes to keep XML info, attributes, text and children nodes, e.g. {"attrs": "@attrs", "text": "#text"} """ if to_str is None: to_str = _to_str_fn(**options) if not anyconfig.utils.is_dict_like(obj): if parent is not None and obj: parent.text = to_str(obj) # Parent is a leaf text node. return parent # All attributes and text should be set already. options = _complement_tag_options(options) (attrs, text, children) = operator.itemgetter(*_ATC)(options) for key, val in anyconfig.compat.iteritems(obj): if key == attrs: _elem_set_attrs(val, parent, to_str) elif key == text: parent.text = to_str(val) elif key == children: for celem in _elem_from_descendants(val, **options): parent.append(celem) else: parent = _get_or_update_parent(key, val, to_str, parent=parent, **options) return ET.ElementTree(parent)
Convert a dict-like object to XML ElementTree. :param obj: Container instance to convert to :param parent: XML ElementTree parent node object or None :param to_str: Callable to convert value to string or None :param options: Keyword options, - tags: Dict of tags for special nodes to keep XML info, attributes, text and children nodes, e.g. {"attrs": "@attrs", "text": "#text"}
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/xml.py#L410-L445
ssato/python-anyconfig
src/anyconfig/backend/xml.py
etree_write
def etree_write(tree, stream): """ Write XML ElementTree 'root' content into 'stream'. :param tree: XML ElementTree object :param stream: File or file-like object can write to """ try: tree.write(stream, encoding="utf-8", xml_declaration=True) except TypeError: tree.write(stream, encoding="unicode", xml_declaration=True)
python
def etree_write(tree, stream): """ Write XML ElementTree 'root' content into 'stream'. :param tree: XML ElementTree object :param stream: File or file-like object can write to """ try: tree.write(stream, encoding="utf-8", xml_declaration=True) except TypeError: tree.write(stream, encoding="unicode", xml_declaration=True)
Write XML ElementTree 'root' content into 'stream'. :param tree: XML ElementTree object :param stream: File or file-like object can write to
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/xml.py#L448-L458
ssato/python-anyconfig
src/anyconfig/backend/xml.py
Parser.load_from_string
def load_from_string(self, content, container, **opts): """ Load config from XML snippet (a string 'content'). :param content: XML snippet string of str (python 2) or bytes (python 3) type :param container: callble to make a container object :param opts: optional keyword parameters passed to :return: Dict-like object holding config parameters """ root = ET.fromstring(content) if anyconfig.compat.IS_PYTHON_3: stream = BytesIO(content) else: stream = anyconfig.compat.StringIO(content) nspaces = _namespaces_from_file(stream) return root_to_container(root, container=container, nspaces=nspaces, **opts)
python
def load_from_string(self, content, container, **opts): """ Load config from XML snippet (a string 'content'). :param content: XML snippet string of str (python 2) or bytes (python 3) type :param container: callble to make a container object :param opts: optional keyword parameters passed to :return: Dict-like object holding config parameters """ root = ET.fromstring(content) if anyconfig.compat.IS_PYTHON_3: stream = BytesIO(content) else: stream = anyconfig.compat.StringIO(content) nspaces = _namespaces_from_file(stream) return root_to_container(root, container=container, nspaces=nspaces, **opts)
Load config from XML snippet (a string 'content'). :param content: XML snippet string of str (python 2) or bytes (python 3) type :param container: callble to make a container object :param opts: optional keyword parameters passed to :return: Dict-like object holding config parameters
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/xml.py#L474-L492
ssato/python-anyconfig
src/anyconfig/backend/xml.py
Parser.load_from_path
def load_from_path(self, filepath, container, **opts): """ :param filepath: XML file path :param container: callble to make a container object :param opts: optional keyword parameters to be sanitized :return: Dict-like object holding config parameters """ root = ET.parse(filepath).getroot() nspaces = _namespaces_from_file(filepath) return root_to_container(root, container=container, nspaces=nspaces, **opts)
python
def load_from_path(self, filepath, container, **opts): """ :param filepath: XML file path :param container: callble to make a container object :param opts: optional keyword parameters to be sanitized :return: Dict-like object holding config parameters """ root = ET.parse(filepath).getroot() nspaces = _namespaces_from_file(filepath) return root_to_container(root, container=container, nspaces=nspaces, **opts)
:param filepath: XML file path :param container: callble to make a container object :param opts: optional keyword parameters to be sanitized :return: Dict-like object holding config parameters
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/xml.py#L494-L505
ssato/python-anyconfig
src/anyconfig/backend/xml.py
Parser.load_from_stream
def load_from_stream(self, stream, container, **opts): """ :param stream: XML file or file-like object :param container: callble to make a container object :param opts: optional keyword parameters to be sanitized :return: Dict-like object holding config parameters """ root = ET.parse(stream).getroot() path = anyconfig.utils.get_path_from_stream(stream) nspaces = _namespaces_from_file(path) return root_to_container(root, container=container, nspaces=nspaces, **opts)
python
def load_from_stream(self, stream, container, **opts): """ :param stream: XML file or file-like object :param container: callble to make a container object :param opts: optional keyword parameters to be sanitized :return: Dict-like object holding config parameters """ root = ET.parse(stream).getroot() path = anyconfig.utils.get_path_from_stream(stream) nspaces = _namespaces_from_file(path) return root_to_container(root, container=container, nspaces=nspaces, **opts)
:param stream: XML file or file-like object :param container: callble to make a container object :param opts: optional keyword parameters to be sanitized :return: Dict-like object holding config parameters
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/xml.py#L507-L519
ssato/python-anyconfig
src/anyconfig/backend/xml.py
Parser.dump_to_string
def dump_to_string(self, cnf, **opts): """ :param cnf: Configuration data to dump :param opts: optional keyword parameters :return: string represents the configuration """ tree = container_to_etree(cnf, **opts) buf = BytesIO() etree_write(tree, buf) return buf.getvalue()
python
def dump_to_string(self, cnf, **opts): """ :param cnf: Configuration data to dump :param opts: optional keyword parameters :return: string represents the configuration """ tree = container_to_etree(cnf, **opts) buf = BytesIO() etree_write(tree, buf) return buf.getvalue()
:param cnf: Configuration data to dump :param opts: optional keyword parameters :return: string represents the configuration
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/xml.py#L521-L531
ssato/python-anyconfig
src/anyconfig/backend/xml.py
Parser.dump_to_stream
def dump_to_stream(self, cnf, stream, **opts): """ :param cnf: Configuration data to dump :param stream: Config file or file like object write to :param opts: optional keyword parameters """ tree = container_to_etree(cnf, **opts) etree_write(tree, stream)
python
def dump_to_stream(self, cnf, stream, **opts): """ :param cnf: Configuration data to dump :param stream: Config file or file like object write to :param opts: optional keyword parameters """ tree = container_to_etree(cnf, **opts) etree_write(tree, stream)
:param cnf: Configuration data to dump :param stream: Config file or file like object write to :param opts: optional keyword parameters
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/xml.py#L533-L540
ssato/python-anyconfig
src/anyconfig/backend/yaml/common.py
filter_from_options
def filter_from_options(key, options): """ :param key: Key str in options :param options: Mapping object :return: New mapping object from 'options' in which the item with 'key' filtered >>> filter_from_options('a', dict(a=1, b=2)) {'b': 2} """ return anyconfig.utils.filter_options([k for k in options.keys() if k != key], options)
python
def filter_from_options(key, options): """ :param key: Key str in options :param options: Mapping object :return: New mapping object from 'options' in which the item with 'key' filtered >>> filter_from_options('a', dict(a=1, b=2)) {'b': 2} """ return anyconfig.utils.filter_options([k for k in options.keys() if k != key], options)
:param key: Key str in options :param options: Mapping object :return: New mapping object from 'options' in which the item with 'key' filtered >>> filter_from_options('a', dict(a=1, b=2)) {'b': 2}
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/yaml/common.py#L12-L23
ssato/python-anyconfig
src/anyconfig/backend/yaml/pyyaml.py
_customized_loader
def _customized_loader(container, loader=Loader, mapping_tag=_MAPPING_TAG): """ Create or update loader with making given callble 'container' to make mapping objects such as dict and OrderedDict, used to construct python object from yaml mapping node internally. :param container: Set container used internally """ def construct_mapping(loader, node, deep=False): """Construct python object from yaml mapping node, based on :meth:`yaml.BaseConstructor.construct_mapping` in PyYAML (MIT). """ loader.flatten_mapping(node) if not isinstance(node, yaml.MappingNode): msg = "expected a mapping node, but found %s" % node.id raise yaml.constructor.ConstructorError(None, None, msg, node.start_mark) mapping = container() for key_node, value_node in node.value: key = loader.construct_object(key_node, deep=deep) try: hash(key) except TypeError as exc: eargs = ("while constructing a mapping", node.start_mark, "found unacceptable key (%s)" % exc, key_node.start_mark) raise yaml.constructor.ConstructorError(*eargs) value = loader.construct_object(value_node, deep=deep) mapping[key] = value return mapping tag = "tag:yaml.org,2002:python/unicode" def construct_ustr(loader, node): """Unicode string constructor""" return loader.construct_scalar(node) try: loader.add_constructor(tag, construct_ustr) except NameError: pass if type(container) != dict: loader.add_constructor(mapping_tag, construct_mapping) return loader
python
def _customized_loader(container, loader=Loader, mapping_tag=_MAPPING_TAG): """ Create or update loader with making given callble 'container' to make mapping objects such as dict and OrderedDict, used to construct python object from yaml mapping node internally. :param container: Set container used internally """ def construct_mapping(loader, node, deep=False): """Construct python object from yaml mapping node, based on :meth:`yaml.BaseConstructor.construct_mapping` in PyYAML (MIT). """ loader.flatten_mapping(node) if not isinstance(node, yaml.MappingNode): msg = "expected a mapping node, but found %s" % node.id raise yaml.constructor.ConstructorError(None, None, msg, node.start_mark) mapping = container() for key_node, value_node in node.value: key = loader.construct_object(key_node, deep=deep) try: hash(key) except TypeError as exc: eargs = ("while constructing a mapping", node.start_mark, "found unacceptable key (%s)" % exc, key_node.start_mark) raise yaml.constructor.ConstructorError(*eargs) value = loader.construct_object(value_node, deep=deep) mapping[key] = value return mapping tag = "tag:yaml.org,2002:python/unicode" def construct_ustr(loader, node): """Unicode string constructor""" return loader.construct_scalar(node) try: loader.add_constructor(tag, construct_ustr) except NameError: pass if type(container) != dict: loader.add_constructor(mapping_tag, construct_mapping) return loader
Create or update loader with making given callble 'container' to make mapping objects such as dict and OrderedDict, used to construct python object from yaml mapping node internally. :param container: Set container used internally
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/yaml/pyyaml.py#L58-L104
ssato/python-anyconfig
src/anyconfig/backend/yaml/pyyaml.py
_customized_dumper
def _customized_dumper(container, dumper=Dumper): """ Coutnerpart of :func:`_customized_loader` for dumpers. """ def container_representer(dumper, data, mapping_tag=_MAPPING_TAG): """Container representer. """ return dumper.represent_mapping(mapping_tag, data.items()) def ustr_representer(dumper, data): """Unicode string representer""" tag = "tag:yaml.org,2002:python/unicode" return dumper.represent_scalar(tag, data) try: dumper.add_representer(unicode, ustr_representer) except NameError: pass if type(container) != dict: dumper.add_representer(container, container_representer) return dumper
python
def _customized_dumper(container, dumper=Dumper): """ Coutnerpart of :func:`_customized_loader` for dumpers. """ def container_representer(dumper, data, mapping_tag=_MAPPING_TAG): """Container representer. """ return dumper.represent_mapping(mapping_tag, data.items()) def ustr_representer(dumper, data): """Unicode string representer""" tag = "tag:yaml.org,2002:python/unicode" return dumper.represent_scalar(tag, data) try: dumper.add_representer(unicode, ustr_representer) except NameError: pass if type(container) != dict: dumper.add_representer(container, container_representer) return dumper
Coutnerpart of :func:`_customized_loader` for dumpers.
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/yaml/pyyaml.py#L107-L128
ssato/python-anyconfig
src/anyconfig/backend/yaml/pyyaml.py
yml_fnc
def yml_fnc(fname, *args, **options): """An wrapper of yaml.safe_load, yaml.load, yaml.safe_dump and yaml.dump. :param fname: "load" or "dump", not checked but it should be OK. see also :func:`yml_load` and :func:`yml_dump` :param args: [stream] for load or [cnf, stream] for dump :param options: keyword args may contain "ac_safe" to load/dump safely """ key = "ac_safe" fnc = getattr(yaml, r"safe_" + fname if options.get(key) else fname) return fnc(*args, **common.filter_from_options(key, options))
python
def yml_fnc(fname, *args, **options): """An wrapper of yaml.safe_load, yaml.load, yaml.safe_dump and yaml.dump. :param fname: "load" or "dump", not checked but it should be OK. see also :func:`yml_load` and :func:`yml_dump` :param args: [stream] for load or [cnf, stream] for dump :param options: keyword args may contain "ac_safe" to load/dump safely """ key = "ac_safe" fnc = getattr(yaml, r"safe_" + fname if options.get(key) else fname) return fnc(*args, **common.filter_from_options(key, options))
An wrapper of yaml.safe_load, yaml.load, yaml.safe_dump and yaml.dump. :param fname: "load" or "dump", not checked but it should be OK. see also :func:`yml_load` and :func:`yml_dump` :param args: [stream] for load or [cnf, stream] for dump :param options: keyword args may contain "ac_safe" to load/dump safely
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/yaml/pyyaml.py#L131-L142
ssato/python-anyconfig
src/anyconfig/backend/yaml/pyyaml.py
yml_load
def yml_load(stream, container, yml_fnc=yml_fnc, **options): """An wrapper of yaml.safe_load and yaml.load. :param stream: a file or file-like object to load YAML content :param container: callble to make a container object :return: Mapping object """ if options.get("ac_safe", False): options = {} # yaml.safe_load does not process Loader opts. elif not options.get("Loader"): maybe_container = options.get("ac_dict", False) if maybe_container and callable(maybe_container): container = maybe_container options["Loader"] = _customized_loader(container) ret = yml_fnc("load", stream, **common.filter_from_options("ac_dict", options)) if ret is None: return container() return ret
python
def yml_load(stream, container, yml_fnc=yml_fnc, **options): """An wrapper of yaml.safe_load and yaml.load. :param stream: a file or file-like object to load YAML content :param container: callble to make a container object :return: Mapping object """ if options.get("ac_safe", False): options = {} # yaml.safe_load does not process Loader opts. elif not options.get("Loader"): maybe_container = options.get("ac_dict", False) if maybe_container and callable(maybe_container): container = maybe_container options["Loader"] = _customized_loader(container) ret = yml_fnc("load", stream, **common.filter_from_options("ac_dict", options)) if ret is None: return container() return ret
An wrapper of yaml.safe_load and yaml.load. :param stream: a file or file-like object to load YAML content :param container: callble to make a container object :return: Mapping object
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/yaml/pyyaml.py#L145-L167
ssato/python-anyconfig
src/anyconfig/backend/yaml/pyyaml.py
yml_dump
def yml_dump(data, stream, yml_fnc=yml_fnc, **options): """An wrapper of yaml.safe_dump and yaml.dump. :param data: Some data to dump :param stream: a file or file-like object to dump YAML data """ _is_dict = anyconfig.utils.is_dict_like(data) if options.get("ac_safe", False): options = {} elif not options.get("Dumper", False) and _is_dict: # TODO: Any other way to get its constructor? maybe_container = options.get("ac_dict", type(data)) options["Dumper"] = _customized_dumper(maybe_container) if _is_dict: # Type information and the order of items are lost on dump currently. data = anyconfig.dicts.convert_to(data, ac_dict=dict) options = common.filter_from_options("ac_dict", options) return yml_fnc("dump", data, stream, **options)
python
def yml_dump(data, stream, yml_fnc=yml_fnc, **options): """An wrapper of yaml.safe_dump and yaml.dump. :param data: Some data to dump :param stream: a file or file-like object to dump YAML data """ _is_dict = anyconfig.utils.is_dict_like(data) if options.get("ac_safe", False): options = {} elif not options.get("Dumper", False) and _is_dict: # TODO: Any other way to get its constructor? maybe_container = options.get("ac_dict", type(data)) options["Dumper"] = _customized_dumper(maybe_container) if _is_dict: # Type information and the order of items are lost on dump currently. data = anyconfig.dicts.convert_to(data, ac_dict=dict) options = common.filter_from_options("ac_dict", options) return yml_fnc("dump", data, stream, **options)
An wrapper of yaml.safe_dump and yaml.dump. :param data: Some data to dump :param stream: a file or file-like object to dump YAML data
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/yaml/pyyaml.py#L170-L190
ssato/python-anyconfig
src/anyconfig/dicts.py
_split_path
def _split_path(path, seps=PATH_SEPS): """ Parse path expression and return list of path items. :param path: Path expression may contain separator chars. :param seps: Separator char candidates. :return: A list of keys to fetch object[s] later. >>> assert _split_path('') == [] >>> assert _split_path('/') == [''] # JSON Pointer spec expects this. >>> for p in ('/a', '.a', 'a', 'a.'): ... assert _split_path(p) == ['a'], p >>> assert _split_path('/a/b/c') == _split_path('a.b.c') == ['a', 'b', 'c'] >>> assert _split_path('abc') == ['abc'] """ if not path: return [] for sep in seps: if sep in path: if path == sep: # Special case, '/' or '.' only. return [''] return [x for x in path.split(sep) if x] return [path]
python
def _split_path(path, seps=PATH_SEPS): """ Parse path expression and return list of path items. :param path: Path expression may contain separator chars. :param seps: Separator char candidates. :return: A list of keys to fetch object[s] later. >>> assert _split_path('') == [] >>> assert _split_path('/') == [''] # JSON Pointer spec expects this. >>> for p in ('/a', '.a', 'a', 'a.'): ... assert _split_path(p) == ['a'], p >>> assert _split_path('/a/b/c') == _split_path('a.b.c') == ['a', 'b', 'c'] >>> assert _split_path('abc') == ['abc'] """ if not path: return [] for sep in seps: if sep in path: if path == sep: # Special case, '/' or '.' only. return [''] return [x for x in path.split(sep) if x] return [path]
Parse path expression and return list of path items. :param path: Path expression may contain separator chars. :param seps: Separator char candidates. :return: A list of keys to fetch object[s] later. >>> assert _split_path('') == [] >>> assert _split_path('/') == [''] # JSON Pointer spec expects this. >>> for p in ('/a', '.a', 'a', 'a.'): ... assert _split_path(p) == ['a'], p >>> assert _split_path('/a/b/c') == _split_path('a.b.c') == ['a', 'b', 'c'] >>> assert _split_path('abc') == ['abc']
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/dicts.py#L50-L74
ssato/python-anyconfig
src/anyconfig/dicts.py
mk_nested_dic
def mk_nested_dic(path, val, seps=PATH_SEPS): """ Make a nested dict iteratively. :param path: Path expression to make a nested dict :param val: Value to set :param seps: Separator char candidates >>> mk_nested_dic("a.b.c", 1) {'a': {'b': {'c': 1}}} >>> mk_nested_dic("/a/b/c", 1) {'a': {'b': {'c': 1}}} """ ret = None for key in reversed(_split_path(path, seps)): ret = {key: val if ret is None else ret.copy()} return ret
python
def mk_nested_dic(path, val, seps=PATH_SEPS): """ Make a nested dict iteratively. :param path: Path expression to make a nested dict :param val: Value to set :param seps: Separator char candidates >>> mk_nested_dic("a.b.c", 1) {'a': {'b': {'c': 1}}} >>> mk_nested_dic("/a/b/c", 1) {'a': {'b': {'c': 1}}} """ ret = None for key in reversed(_split_path(path, seps)): ret = {key: val if ret is None else ret.copy()} return ret
Make a nested dict iteratively. :param path: Path expression to make a nested dict :param val: Value to set :param seps: Separator char candidates >>> mk_nested_dic("a.b.c", 1) {'a': {'b': {'c': 1}}} >>> mk_nested_dic("/a/b/c", 1) {'a': {'b': {'c': 1}}}
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/dicts.py#L77-L94
ssato/python-anyconfig
src/anyconfig/dicts.py
get
def get(dic, path, seps=PATH_SEPS, idx_reg=_JSNP_GET_ARRAY_IDX_REG): """getter for nested dicts. :param dic: a dict[-like] object :param path: Path expression to point object wanted :param seps: Separator char candidates :return: A tuple of (result_object, error_message) >>> d = {'a': {'b': {'c': 0, 'd': [1, 2]}}, '': 3} >>> assert get(d, '/') == (3, '') # key becomes '' (empty string). >>> assert get(d, "/a/b/c") == (0, '') >>> sorted(get(d, "a.b")[0].items()) [('c', 0), ('d', [1, 2])] >>> (get(d, "a.b.d"), get(d, "/a/b/d/1")) (([1, 2], ''), (2, '')) >>> get(d, "a.b.key_not_exist") # doctest: +ELLIPSIS (None, "'...'") >>> get(d, "/a/b/d/2") (None, 'list index out of range') >>> get(d, "/a/b/d/-") # doctest: +ELLIPSIS (None, 'list indices must be integers...') """ items = [_jsnp_unescape(p) for p in _split_path(path, seps)] if not items: return (dic, '') try: if len(items) == 1: return (dic[items[0]], '') prnt = functools.reduce(operator.getitem, items[:-1], dic) arr = anyconfig.utils.is_list_like(prnt) and idx_reg.match(items[-1]) return (prnt[int(items[-1])], '') if arr else (prnt[items[-1]], '') except (TypeError, KeyError, IndexError) as exc: return (None, str(exc))
python
def get(dic, path, seps=PATH_SEPS, idx_reg=_JSNP_GET_ARRAY_IDX_REG): """getter for nested dicts. :param dic: a dict[-like] object :param path: Path expression to point object wanted :param seps: Separator char candidates :return: A tuple of (result_object, error_message) >>> d = {'a': {'b': {'c': 0, 'd': [1, 2]}}, '': 3} >>> assert get(d, '/') == (3, '') # key becomes '' (empty string). >>> assert get(d, "/a/b/c") == (0, '') >>> sorted(get(d, "a.b")[0].items()) [('c', 0), ('d', [1, 2])] >>> (get(d, "a.b.d"), get(d, "/a/b/d/1")) (([1, 2], ''), (2, '')) >>> get(d, "a.b.key_not_exist") # doctest: +ELLIPSIS (None, "'...'") >>> get(d, "/a/b/d/2") (None, 'list index out of range') >>> get(d, "/a/b/d/-") # doctest: +ELLIPSIS (None, 'list indices must be integers...') """ items = [_jsnp_unescape(p) for p in _split_path(path, seps)] if not items: return (dic, '') try: if len(items) == 1: return (dic[items[0]], '') prnt = functools.reduce(operator.getitem, items[:-1], dic) arr = anyconfig.utils.is_list_like(prnt) and idx_reg.match(items[-1]) return (prnt[int(items[-1])], '') if arr else (prnt[items[-1]], '') except (TypeError, KeyError, IndexError) as exc: return (None, str(exc))
getter for nested dicts. :param dic: a dict[-like] object :param path: Path expression to point object wanted :param seps: Separator char candidates :return: A tuple of (result_object, error_message) >>> d = {'a': {'b': {'c': 0, 'd': [1, 2]}}, '': 3} >>> assert get(d, '/') == (3, '') # key becomes '' (empty string). >>> assert get(d, "/a/b/c") == (0, '') >>> sorted(get(d, "a.b")[0].items()) [('c', 0), ('d', [1, 2])] >>> (get(d, "a.b.d"), get(d, "/a/b/d/1")) (([1, 2], ''), (2, '')) >>> get(d, "a.b.key_not_exist") # doctest: +ELLIPSIS (None, "'...'") >>> get(d, "/a/b/d/2") (None, 'list index out of range') >>> get(d, "/a/b/d/-") # doctest: +ELLIPSIS (None, 'list indices must be integers...')
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/dicts.py#L97-L131
ssato/python-anyconfig
src/anyconfig/dicts.py
set_
def set_(dic, path, val, seps=PATH_SEPS): """setter for nested dicts. :param dic: a dict[-like] object support recursive merge operations :param path: Path expression to point object wanted :param seps: Separator char candidates >>> d = dict(a=1, b=dict(c=2, )) >>> set_(d, 'a.b.d', 3) >>> d['a']['b']['d'] 3 """ merge(dic, mk_nested_dic(path, val, seps), ac_merge=MS_DICTS)
python
def set_(dic, path, val, seps=PATH_SEPS): """setter for nested dicts. :param dic: a dict[-like] object support recursive merge operations :param path: Path expression to point object wanted :param seps: Separator char candidates >>> d = dict(a=1, b=dict(c=2, )) >>> set_(d, 'a.b.d', 3) >>> d['a']['b']['d'] 3 """ merge(dic, mk_nested_dic(path, val, seps), ac_merge=MS_DICTS)
setter for nested dicts. :param dic: a dict[-like] object support recursive merge operations :param path: Path expression to point object wanted :param seps: Separator char candidates >>> d = dict(a=1, b=dict(c=2, )) >>> set_(d, 'a.b.d', 3) >>> d['a']['b']['d'] 3
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/dicts.py#L134-L146
ssato/python-anyconfig
src/anyconfig/dicts.py
_update_with_replace
def _update_with_replace(self, other, key, val=None, **options): """ Replace value of a mapping object 'self' with 'other' has if both have same keys on update. Otherwise, just keep the value of 'self'. :param self: mapping object to update with 'other' :param other: mapping object to update 'self' :param key: key of mapping object to update :param val: value to update self alternatively :return: None but 'self' will be updated """ self[key] = other[key] if val is None else val
python
def _update_with_replace(self, other, key, val=None, **options): """ Replace value of a mapping object 'self' with 'other' has if both have same keys on update. Otherwise, just keep the value of 'self'. :param self: mapping object to update with 'other' :param other: mapping object to update 'self' :param key: key of mapping object to update :param val: value to update self alternatively :return: None but 'self' will be updated """ self[key] = other[key] if val is None else val
Replace value of a mapping object 'self' with 'other' has if both have same keys on update. Otherwise, just keep the value of 'self'. :param self: mapping object to update with 'other' :param other: mapping object to update 'self' :param key: key of mapping object to update :param val: value to update self alternatively :return: None but 'self' will be updated
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/dicts.py#L161-L173
ssato/python-anyconfig
src/anyconfig/dicts.py
_merge_list
def _merge_list(self, key, lst): """ :param key: self[key] will be updated :param lst: Other list to merge """ self[key] += [x for x in lst if x not in self[key]]
python
def _merge_list(self, key, lst): """ :param key: self[key] will be updated :param lst: Other list to merge """ self[key] += [x for x in lst if x not in self[key]]
:param key: self[key] will be updated :param lst: Other list to merge
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/dicts.py#L192-L197
ssato/python-anyconfig
src/anyconfig/dicts.py
_update_with_merge
def _update_with_merge(self, other, key, val=None, merge_lists=False, **options): """ Merge the value of self with other's recursively. Behavior of merge will be vary depends on types of original and new values. - mapping vs. mapping -> merge recursively - list vs. list -> vary depends on 'merge_lists'. see its description. :param other: a dict[-like] object or a list of (key, value) tuples :param key: key of mapping object to update :param val: value to update self[key] :param merge_lists: Merge not only dicts but also lists. For example, [1, 2, 3], [3, 4] ==> [1, 2, 3, 4] [1, 2, 2], [2, 4] ==> [1, 2, 2, 4] :return: None but 'self' will be updated """ if val is None: val = other[key] if key in self: val0 = self[key] # Original value if anyconfig.utils.is_dict_like(val0): # It needs recursive updates. merge(self[key], val, merge_lists=merge_lists, **options) elif merge_lists and _are_list_like(val, val0): _merge_list(self, key, val) else: _merge_other(self, key, val) else: self[key] = val
python
def _update_with_merge(self, other, key, val=None, merge_lists=False, **options): """ Merge the value of self with other's recursively. Behavior of merge will be vary depends on types of original and new values. - mapping vs. mapping -> merge recursively - list vs. list -> vary depends on 'merge_lists'. see its description. :param other: a dict[-like] object or a list of (key, value) tuples :param key: key of mapping object to update :param val: value to update self[key] :param merge_lists: Merge not only dicts but also lists. For example, [1, 2, 3], [3, 4] ==> [1, 2, 3, 4] [1, 2, 2], [2, 4] ==> [1, 2, 2, 4] :return: None but 'self' will be updated """ if val is None: val = other[key] if key in self: val0 = self[key] # Original value if anyconfig.utils.is_dict_like(val0): # It needs recursive updates. merge(self[key], val, merge_lists=merge_lists, **options) elif merge_lists and _are_list_like(val, val0): _merge_list(self, key, val) else: _merge_other(self, key, val) else: self[key] = val
Merge the value of self with other's recursively. Behavior of merge will be vary depends on types of original and new values. - mapping vs. mapping -> merge recursively - list vs. list -> vary depends on 'merge_lists'. see its description. :param other: a dict[-like] object or a list of (key, value) tuples :param key: key of mapping object to update :param val: value to update self[key] :param merge_lists: Merge not only dicts but also lists. For example, [1, 2, 3], [3, 4] ==> [1, 2, 3, 4] [1, 2, 2], [2, 4] ==> [1, 2, 2, 4] :return: None but 'self' will be updated
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/dicts.py#L208-L240
ssato/python-anyconfig
src/anyconfig/dicts.py
_update_with_merge_lists
def _update_with_merge_lists(self, other, key, val=None, **options): """ Similar to _update_with_merge but merge lists always. :param self: mapping object to update with 'other' :param other: mapping object to update 'self' :param key: key of mapping object to update :param val: value to update self alternatively :return: None but 'self' will be updated """ _update_with_merge(self, other, key, val=val, merge_lists=True, **options)
python
def _update_with_merge_lists(self, other, key, val=None, **options): """ Similar to _update_with_merge but merge lists always. :param self: mapping object to update with 'other' :param other: mapping object to update 'self' :param key: key of mapping object to update :param val: value to update self alternatively :return: None but 'self' will be updated """ _update_with_merge(self, other, key, val=val, merge_lists=True, **options)
Similar to _update_with_merge but merge lists always. :param self: mapping object to update with 'other' :param other: mapping object to update 'self' :param key: key of mapping object to update :param val: value to update self alternatively :return: None but 'self' will be updated
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/dicts.py#L243-L254
ssato/python-anyconfig
src/anyconfig/dicts.py
_get_update_fn
def _get_update_fn(strategy): """ Select dict-like class based on merge strategy and orderness of keys. :param merge: Specify strategy from MERGE_STRATEGIES of how to merge dicts. :return: Callable to update objects """ if strategy is None: strategy = MS_DICTS try: return _MERGE_FNS[strategy] except KeyError: if callable(strategy): return strategy raise ValueError("Wrong merge strategy: %r" % strategy)
python
def _get_update_fn(strategy): """ Select dict-like class based on merge strategy and orderness of keys. :param merge: Specify strategy from MERGE_STRATEGIES of how to merge dicts. :return: Callable to update objects """ if strategy is None: strategy = MS_DICTS try: return _MERGE_FNS[strategy] except KeyError: if callable(strategy): return strategy raise ValueError("Wrong merge strategy: %r" % strategy)
Select dict-like class based on merge strategy and orderness of keys. :param merge: Specify strategy from MERGE_STRATEGIES of how to merge dicts. :return: Callable to update objects
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/dicts.py#L263-L278
ssato/python-anyconfig
src/anyconfig/dicts.py
merge
def merge(self, other, ac_merge=MS_DICTS, **options): """ Update (merge) a mapping object 'self' with other mapping object or an iterable yields (key, value) tuples based on merge strategy 'ac_merge'. :param others: a list of dict[-like] objects or (key, value) tuples :param another: optional keyword arguments to update self more :param ac_merge: Merge strategy to choose """ _update_fn = _get_update_fn(ac_merge) if hasattr(other, "keys"): for key in other: _update_fn(self, other, key, **options) else: try: for key, val in other: _update_fn(self, other, key, val=val, **options) except (ValueError, TypeError) as exc: # Re-raise w/ info. raise type(exc)("%s other=%r" % (str(exc), other))
python
def merge(self, other, ac_merge=MS_DICTS, **options): """ Update (merge) a mapping object 'self' with other mapping object or an iterable yields (key, value) tuples based on merge strategy 'ac_merge'. :param others: a list of dict[-like] objects or (key, value) tuples :param another: optional keyword arguments to update self more :param ac_merge: Merge strategy to choose """ _update_fn = _get_update_fn(ac_merge) if hasattr(other, "keys"): for key in other: _update_fn(self, other, key, **options) else: try: for key, val in other: _update_fn(self, other, key, val=val, **options) except (ValueError, TypeError) as exc: # Re-raise w/ info. raise type(exc)("%s other=%r" % (str(exc), other))
Update (merge) a mapping object 'self' with other mapping object or an iterable yields (key, value) tuples based on merge strategy 'ac_merge'. :param others: a list of dict[-like] objects or (key, value) tuples :param another: optional keyword arguments to update self more :param ac_merge: Merge strategy to choose
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/dicts.py#L281-L300
ssato/python-anyconfig
src/anyconfig/dicts.py
_make_recur
def _make_recur(obj, make_fn, ac_ordered=False, ac_dict=None, **options): """ :param obj: A mapping objects or other primitive object :param make_fn: Function to make/convert to :param ac_ordered: Use OrderedDict instead of dict to keep order of items :param ac_dict: Callable to convert 'obj' to mapping object :param options: Optional keyword arguments. :return: Mapping object """ if ac_dict is None: ac_dict = anyconfig.compat.OrderedDict if ac_ordered else dict return ac_dict((k, None if v is None else make_fn(v, **options)) for k, v in obj.items())
python
def _make_recur(obj, make_fn, ac_ordered=False, ac_dict=None, **options): """ :param obj: A mapping objects or other primitive object :param make_fn: Function to make/convert to :param ac_ordered: Use OrderedDict instead of dict to keep order of items :param ac_dict: Callable to convert 'obj' to mapping object :param options: Optional keyword arguments. :return: Mapping object """ if ac_dict is None: ac_dict = anyconfig.compat.OrderedDict if ac_ordered else dict return ac_dict((k, None if v is None else make_fn(v, **options)) for k, v in obj.items())
:param obj: A mapping objects or other primitive object :param make_fn: Function to make/convert to :param ac_ordered: Use OrderedDict instead of dict to keep order of items :param ac_dict: Callable to convert 'obj' to mapping object :param options: Optional keyword arguments. :return: Mapping object
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/dicts.py#L303-L317
ssato/python-anyconfig
src/anyconfig/dicts.py
_make_iter
def _make_iter(obj, make_fn, **options): """ :param obj: A mapping objects or other primitive object :param make_fn: Function to make/convert to :param options: Optional keyword arguments. :return: Mapping object """ return type(obj)(make_fn(v, **options) for v in obj)
python
def _make_iter(obj, make_fn, **options): """ :param obj: A mapping objects or other primitive object :param make_fn: Function to make/convert to :param options: Optional keyword arguments. :return: Mapping object """ return type(obj)(make_fn(v, **options) for v in obj)
:param obj: A mapping objects or other primitive object :param make_fn: Function to make/convert to :param options: Optional keyword arguments. :return: Mapping object
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/dicts.py#L320-L328
ssato/python-anyconfig
src/anyconfig/dicts.py
convert_to
def convert_to(obj, ac_ordered=False, ac_dict=None, **options): """ Convert a mapping objects to a dict or object of 'to_type' recursively. Borrowed basic idea and implementation from bunch.unbunchify. (bunch is distributed under MIT license same as this.) :param obj: A mapping objects or other primitive object :param ac_ordered: Use OrderedDict instead of dict to keep order of items :param ac_dict: Callable to convert 'obj' to mapping object :param options: Optional keyword arguments. :return: A dict or OrderedDict or object of 'cls' >>> OD = anyconfig.compat.OrderedDict >>> convert_to(OD((('a', 1) ,)), cls=dict) {'a': 1} >>> convert_to(OD((('a', OD((('b', OD((('c', 1), ))), ))), )), cls=dict) {'a': {'b': {'c': 1}}} """ options.update(ac_ordered=ac_ordered, ac_dict=ac_dict) if anyconfig.utils.is_dict_like(obj): return _make_recur(obj, convert_to, **options) if anyconfig.utils.is_list_like(obj): return _make_iter(obj, convert_to, **options) return obj
python
def convert_to(obj, ac_ordered=False, ac_dict=None, **options): """ Convert a mapping objects to a dict or object of 'to_type' recursively. Borrowed basic idea and implementation from bunch.unbunchify. (bunch is distributed under MIT license same as this.) :param obj: A mapping objects or other primitive object :param ac_ordered: Use OrderedDict instead of dict to keep order of items :param ac_dict: Callable to convert 'obj' to mapping object :param options: Optional keyword arguments. :return: A dict or OrderedDict or object of 'cls' >>> OD = anyconfig.compat.OrderedDict >>> convert_to(OD((('a', 1) ,)), cls=dict) {'a': 1} >>> convert_to(OD((('a', OD((('b', OD((('c', 1), ))), ))), )), cls=dict) {'a': {'b': {'c': 1}}} """ options.update(ac_ordered=ac_ordered, ac_dict=ac_dict) if anyconfig.utils.is_dict_like(obj): return _make_recur(obj, convert_to, **options) if anyconfig.utils.is_list_like(obj): return _make_iter(obj, convert_to, **options) return obj
Convert a mapping objects to a dict or object of 'to_type' recursively. Borrowed basic idea and implementation from bunch.unbunchify. (bunch is distributed under MIT license same as this.) :param obj: A mapping objects or other primitive object :param ac_ordered: Use OrderedDict instead of dict to keep order of items :param ac_dict: Callable to convert 'obj' to mapping object :param options: Optional keyword arguments. :return: A dict or OrderedDict or object of 'cls' >>> OD = anyconfig.compat.OrderedDict >>> convert_to(OD((('a', 1) ,)), cls=dict) {'a': 1} >>> convert_to(OD((('a', OD((('b', OD((('c', 1), ))), ))), )), cls=dict) {'a': {'b': {'c': 1}}}
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/dicts.py#L331-L356
ssato/python-anyconfig
src/anyconfig/backend/properties.py
_parseline
def _parseline(line): """ Parse a line of Java properties file. :param line: A string to parse, must not start with ' ', '#' or '!' (comment) :return: A tuple of (key, value), both key and value may be None >>> _parseline(" ") (None, '') >>> _parseline("aaa:") ('aaa', '') >>> _parseline(" aaa:") ('aaa', '') >>> _parseline("aaa") ('aaa', '') >>> _parseline("url = http://localhost") ('url', 'http://localhost') >>> _parseline("calendar.japanese.type: LocalGregorianCalendar") ('calendar.japanese.type', 'LocalGregorianCalendar') """ pair = re.split(r"(?:\s+)?(?:(?<!\\)[=:])", line.strip(), 1) key = pair[0].rstrip() if len(pair) < 2: LOGGER.warning("Invalid line found: %s", line) return (key or None, '') return (key, pair[1].strip())
python
def _parseline(line): """ Parse a line of Java properties file. :param line: A string to parse, must not start with ' ', '#' or '!' (comment) :return: A tuple of (key, value), both key and value may be None >>> _parseline(" ") (None, '') >>> _parseline("aaa:") ('aaa', '') >>> _parseline(" aaa:") ('aaa', '') >>> _parseline("aaa") ('aaa', '') >>> _parseline("url = http://localhost") ('url', 'http://localhost') >>> _parseline("calendar.japanese.type: LocalGregorianCalendar") ('calendar.japanese.type', 'LocalGregorianCalendar') """ pair = re.split(r"(?:\s+)?(?:(?<!\\)[=:])", line.strip(), 1) key = pair[0].rstrip() if len(pair) < 2: LOGGER.warning("Invalid line found: %s", line) return (key or None, '') return (key, pair[1].strip())
Parse a line of Java properties file. :param line: A string to parse, must not start with ' ', '#' or '!' (comment) :return: A tuple of (key, value), both key and value may be None >>> _parseline(" ") (None, '') >>> _parseline("aaa:") ('aaa', '') >>> _parseline(" aaa:") ('aaa', '') >>> _parseline("aaa") ('aaa', '') >>> _parseline("url = http://localhost") ('url', 'http://localhost') >>> _parseline("calendar.japanese.type: LocalGregorianCalendar") ('calendar.japanese.type', 'LocalGregorianCalendar')
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/properties.py#L46-L74
ssato/python-anyconfig
src/anyconfig/backend/properties.py
_pre_process_line
def _pre_process_line(line, comment_markers=_COMMENT_MARKERS): """ Preprocess a line in properties; strip comments, etc. :param line: A string not starting w/ any white spaces and ending w/ line breaks. It may be empty. see also: :func:`load`. :param comment_markers: Comment markers, e.g. '#' (hash) >>> _pre_process_line('') is None True >>> s0 = "calendar.japanese.type: LocalGregorianCalendar" >>> _pre_process_line("# " + s0) is None True >>> _pre_process_line("! " + s0) is None True >>> _pre_process_line(s0 + "# comment") 'calendar.japanese.type: LocalGregorianCalendar# comment' """ if not line: return None if any(c in line for c in comment_markers): if line.startswith(comment_markers): return None return line
python
def _pre_process_line(line, comment_markers=_COMMENT_MARKERS): """ Preprocess a line in properties; strip comments, etc. :param line: A string not starting w/ any white spaces and ending w/ line breaks. It may be empty. see also: :func:`load`. :param comment_markers: Comment markers, e.g. '#' (hash) >>> _pre_process_line('') is None True >>> s0 = "calendar.japanese.type: LocalGregorianCalendar" >>> _pre_process_line("# " + s0) is None True >>> _pre_process_line("! " + s0) is None True >>> _pre_process_line(s0 + "# comment") 'calendar.japanese.type: LocalGregorianCalendar# comment' """ if not line: return None if any(c in line for c in comment_markers): if line.startswith(comment_markers): return None return line
Preprocess a line in properties; strip comments, etc. :param line: A string not starting w/ any white spaces and ending w/ line breaks. It may be empty. see also: :func:`load`. :param comment_markers: Comment markers, e.g. '#' (hash) >>> _pre_process_line('') is None True >>> s0 = "calendar.japanese.type: LocalGregorianCalendar" >>> _pre_process_line("# " + s0) is None True >>> _pre_process_line("! " + s0) is None True >>> _pre_process_line(s0 + "# comment") 'calendar.japanese.type: LocalGregorianCalendar# comment'
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/properties.py#L77-L103
ssato/python-anyconfig
src/anyconfig/backend/properties.py
load
def load(stream, container=dict, comment_markers=_COMMENT_MARKERS): """ Load and parse Java properties file given as a fiel or file-like object 'stream'. :param stream: A file or file like object of Java properties files :param container: Factory function to create a dict-like object to store properties :param comment_markers: Comment markers, e.g. '#' (hash) :return: Dict-like object holding properties >>> to_strm = anyconfig.compat.StringIO >>> s0 = "calendar.japanese.type: LocalGregorianCalendar" >>> load(to_strm('')) {} >>> load(to_strm("# " + s0)) {} >>> load(to_strm("! " + s0)) {} >>> load(to_strm("calendar.japanese.type:")) {'calendar.japanese.type': ''} >>> load(to_strm(s0)) {'calendar.japanese.type': 'LocalGregorianCalendar'} >>> load(to_strm(s0 + "# ...")) {'calendar.japanese.type': 'LocalGregorianCalendar# ...'} >>> s1 = r"key=a\\:b" >>> load(to_strm(s1)) {'key': 'a:b'} >>> s2 = '''application/postscript: \\ ... x=Postscript File;y=.eps,.ps ... ''' >>> load(to_strm(s2)) {'application/postscript': 'x=Postscript File;y=.eps,.ps'} """ ret = container() prev = "" for line in stream.readlines(): line = _pre_process_line(prev + line.strip().rstrip(), comment_markers) # I don't think later case may happen but just in case. if line is None or not line: continue prev = "" # re-initialize for later use. if line.endswith("\\"): prev += line.rstrip(" \\") continue (key, val) = _parseline(line) if key is None: LOGGER.warning("Failed to parse the line: %s", line) continue ret[key] = unescape(val) return ret
python
def load(stream, container=dict, comment_markers=_COMMENT_MARKERS): """ Load and parse Java properties file given as a fiel or file-like object 'stream'. :param stream: A file or file like object of Java properties files :param container: Factory function to create a dict-like object to store properties :param comment_markers: Comment markers, e.g. '#' (hash) :return: Dict-like object holding properties >>> to_strm = anyconfig.compat.StringIO >>> s0 = "calendar.japanese.type: LocalGregorianCalendar" >>> load(to_strm('')) {} >>> load(to_strm("# " + s0)) {} >>> load(to_strm("! " + s0)) {} >>> load(to_strm("calendar.japanese.type:")) {'calendar.japanese.type': ''} >>> load(to_strm(s0)) {'calendar.japanese.type': 'LocalGregorianCalendar'} >>> load(to_strm(s0 + "# ...")) {'calendar.japanese.type': 'LocalGregorianCalendar# ...'} >>> s1 = r"key=a\\:b" >>> load(to_strm(s1)) {'key': 'a:b'} >>> s2 = '''application/postscript: \\ ... x=Postscript File;y=.eps,.ps ... ''' >>> load(to_strm(s2)) {'application/postscript': 'x=Postscript File;y=.eps,.ps'} """ ret = container() prev = "" for line in stream.readlines(): line = _pre_process_line(prev + line.strip().rstrip(), comment_markers) # I don't think later case may happen but just in case. if line is None or not line: continue prev = "" # re-initialize for later use. if line.endswith("\\"): prev += line.rstrip(" \\") continue (key, val) = _parseline(line) if key is None: LOGGER.warning("Failed to parse the line: %s", line) continue ret[key] = unescape(val) return ret
Load and parse Java properties file given as a fiel or file-like object 'stream'. :param stream: A file or file like object of Java properties files :param container: Factory function to create a dict-like object to store properties :param comment_markers: Comment markers, e.g. '#' (hash) :return: Dict-like object holding properties >>> to_strm = anyconfig.compat.StringIO >>> s0 = "calendar.japanese.type: LocalGregorianCalendar" >>> load(to_strm('')) {} >>> load(to_strm("# " + s0)) {} >>> load(to_strm("! " + s0)) {} >>> load(to_strm("calendar.japanese.type:")) {'calendar.japanese.type': ''} >>> load(to_strm(s0)) {'calendar.japanese.type': 'LocalGregorianCalendar'} >>> load(to_strm(s0 + "# ...")) {'calendar.japanese.type': 'LocalGregorianCalendar# ...'} >>> s1 = r"key=a\\:b" >>> load(to_strm(s1)) {'key': 'a:b'} >>> s2 = '''application/postscript: \\ ... x=Postscript File;y=.eps,.ps ... ''' >>> load(to_strm(s2)) {'application/postscript': 'x=Postscript File;y=.eps,.ps'}
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/properties.py#L136-L193
ssato/python-anyconfig
src/anyconfig/template.py
copen
def copen(filepath, flag='r', encoding=None): """ FIXME: How to test this ? >>> c = copen(__file__) >>> c is not None True """ if encoding is None: encoding = locale.getdefaultlocale()[1] return codecs.open(filepath, flag, encoding)
python
def copen(filepath, flag='r', encoding=None): """ FIXME: How to test this ? >>> c = copen(__file__) >>> c is not None True """ if encoding is None: encoding = locale.getdefaultlocale()[1] return codecs.open(filepath, flag, encoding)
FIXME: How to test this ? >>> c = copen(__file__) >>> c is not None True
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/template.py#L50-L62
ssato/python-anyconfig
src/anyconfig/template.py
make_template_paths
def make_template_paths(template_file, paths=None): """ Make up a list of template search paths from given 'template_file' (absolute or relative path to the template file) and/or 'paths' (a list of template search paths given by user). NOTE: User-given 'paths' will take higher priority over a dir of template_file. :param template_file: Absolute or relative path to the template file :param paths: A list of template search paths :return: List of template paths ([str]) >>> make_template_paths("/path/to/a/template") ['/path/to/a'] >>> make_template_paths("/path/to/a/template", ["/tmp"]) ['/tmp', '/path/to/a'] >>> os.chdir("/tmp") >>> make_template_paths("./path/to/a/template") ['/tmp/path/to/a'] >>> make_template_paths("./path/to/a/template", ["/tmp"]) ['/tmp', '/tmp/path/to/a'] """ tmpldir = os.path.abspath(os.path.dirname(template_file)) return [tmpldir] if paths is None else paths + [tmpldir]
python
def make_template_paths(template_file, paths=None): """ Make up a list of template search paths from given 'template_file' (absolute or relative path to the template file) and/or 'paths' (a list of template search paths given by user). NOTE: User-given 'paths' will take higher priority over a dir of template_file. :param template_file: Absolute or relative path to the template file :param paths: A list of template search paths :return: List of template paths ([str]) >>> make_template_paths("/path/to/a/template") ['/path/to/a'] >>> make_template_paths("/path/to/a/template", ["/tmp"]) ['/tmp', '/path/to/a'] >>> os.chdir("/tmp") >>> make_template_paths("./path/to/a/template") ['/tmp/path/to/a'] >>> make_template_paths("./path/to/a/template", ["/tmp"]) ['/tmp', '/tmp/path/to/a'] """ tmpldir = os.path.abspath(os.path.dirname(template_file)) return [tmpldir] if paths is None else paths + [tmpldir]
Make up a list of template search paths from given 'template_file' (absolute or relative path to the template file) and/or 'paths' (a list of template search paths given by user). NOTE: User-given 'paths' will take higher priority over a dir of template_file. :param template_file: Absolute or relative path to the template file :param paths: A list of template search paths :return: List of template paths ([str]) >>> make_template_paths("/path/to/a/template") ['/path/to/a'] >>> make_template_paths("/path/to/a/template", ["/tmp"]) ['/tmp', '/path/to/a'] >>> os.chdir("/tmp") >>> make_template_paths("./path/to/a/template") ['/tmp/path/to/a'] >>> make_template_paths("./path/to/a/template", ["/tmp"]) ['/tmp', '/tmp/path/to/a']
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/template.py#L65-L89
ssato/python-anyconfig
src/anyconfig/template.py
render_s
def render_s(tmpl_s, ctx=None, paths=None, filters=None): """ Compile and render given template string 'tmpl_s' with context 'context'. :param tmpl_s: Template string :param ctx: Context dict needed to instantiate templates :param paths: Template search paths :param filters: Custom filters to add into template engine :return: Compiled result (str) >>> render_s("aaa") == "aaa" True >>> s = render_s('a = {{ a }}, b = "{{ b }}"', {'a': 1, 'b': 'bbb'}) >>> if SUPPORTED: ... assert s == 'a = 1, b = "bbb"' """ if paths is None: paths = [os.curdir] env = tmpl_env(paths) if env is None: return tmpl_s if filters is not None: env.filters.update(filters) if ctx is None: ctx = {} return tmpl_env(paths).from_string(tmpl_s).render(**ctx)
python
def render_s(tmpl_s, ctx=None, paths=None, filters=None): """ Compile and render given template string 'tmpl_s' with context 'context'. :param tmpl_s: Template string :param ctx: Context dict needed to instantiate templates :param paths: Template search paths :param filters: Custom filters to add into template engine :return: Compiled result (str) >>> render_s("aaa") == "aaa" True >>> s = render_s('a = {{ a }}, b = "{{ b }}"', {'a': 1, 'b': 'bbb'}) >>> if SUPPORTED: ... assert s == 'a = 1, b = "bbb"' """ if paths is None: paths = [os.curdir] env = tmpl_env(paths) if env is None: return tmpl_s if filters is not None: env.filters.update(filters) if ctx is None: ctx = {} return tmpl_env(paths).from_string(tmpl_s).render(**ctx)
Compile and render given template string 'tmpl_s' with context 'context'. :param tmpl_s: Template string :param ctx: Context dict needed to instantiate templates :param paths: Template search paths :param filters: Custom filters to add into template engine :return: Compiled result (str) >>> render_s("aaa") == "aaa" True >>> s = render_s('a = {{ a }}, b = "{{ b }}"', {'a': 1, 'b': 'bbb'}) >>> if SUPPORTED: ... assert s == 'a = 1, b = "bbb"'
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/template.py#L92-L122
ssato/python-anyconfig
src/anyconfig/template.py
render_impl
def render_impl(template_file, ctx=None, paths=None, filters=None): """ :param template_file: Absolute or relative path to the template file :param ctx: Context dict needed to instantiate templates :param filters: Custom filters to add into template engine :return: Compiled result (str) """ env = tmpl_env(make_template_paths(template_file, paths)) if env is None: return copen(template_file).read() if filters is not None: env.filters.update(filters) if ctx is None: ctx = {} return env.get_template(os.path.basename(template_file)).render(**ctx)
python
def render_impl(template_file, ctx=None, paths=None, filters=None): """ :param template_file: Absolute or relative path to the template file :param ctx: Context dict needed to instantiate templates :param filters: Custom filters to add into template engine :return: Compiled result (str) """ env = tmpl_env(make_template_paths(template_file, paths)) if env is None: return copen(template_file).read() if filters is not None: env.filters.update(filters) if ctx is None: ctx = {} return env.get_template(os.path.basename(template_file)).render(**ctx)
:param template_file: Absolute or relative path to the template file :param ctx: Context dict needed to instantiate templates :param filters: Custom filters to add into template engine :return: Compiled result (str)
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/template.py#L125-L143
ssato/python-anyconfig
src/anyconfig/template.py
render
def render(filepath, ctx=None, paths=None, ask=False, filters=None): """ Compile and render template and return the result as a string. :param template_file: Absolute or relative path to the template file :param ctx: Context dict needed to instantiate templates :param paths: Template search paths :param ask: Ask user for missing template location if True :param filters: Custom filters to add into template engine :return: Compiled result (str) """ try: return render_impl(filepath, ctx, paths, filters) except TemplateNotFound as mtmpl: if not ask: raise usr_tmpl = anyconfig.compat.raw_input(os.linesep + "" "*** Missing template " "'%s'. Please enter absolute " "or relative path starting from " "'.' to the template file: " % mtmpl) usr_tmpl = os.path.normpath(usr_tmpl.strip()) paths = make_template_paths(usr_tmpl, paths) return render_impl(usr_tmpl, ctx, paths, filters)
python
def render(filepath, ctx=None, paths=None, ask=False, filters=None): """ Compile and render template and return the result as a string. :param template_file: Absolute or relative path to the template file :param ctx: Context dict needed to instantiate templates :param paths: Template search paths :param ask: Ask user for missing template location if True :param filters: Custom filters to add into template engine :return: Compiled result (str) """ try: return render_impl(filepath, ctx, paths, filters) except TemplateNotFound as mtmpl: if not ask: raise usr_tmpl = anyconfig.compat.raw_input(os.linesep + "" "*** Missing template " "'%s'. Please enter absolute " "or relative path starting from " "'.' to the template file: " % mtmpl) usr_tmpl = os.path.normpath(usr_tmpl.strip()) paths = make_template_paths(usr_tmpl, paths) return render_impl(usr_tmpl, ctx, paths, filters)
Compile and render template and return the result as a string. :param template_file: Absolute or relative path to the template file :param ctx: Context dict needed to instantiate templates :param paths: Template search paths :param ask: Ask user for missing template location if True :param filters: Custom filters to add into template engine :return: Compiled result (str)
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/template.py#L146-L172
ssato/python-anyconfig
src/anyconfig/template.py
try_render
def try_render(filepath=None, content=None, **options): """ Compile and render template and return the result as a string. :param filepath: Absolute or relative path to the template file :param content: Template content (str) :param options: Keyword options passed to :func:`render` defined above. :return: Compiled result (str) or None """ if filepath is None and content is None: raise ValueError("Either 'path' or 'content' must be some value!") tmpl_s = filepath or content[:10] + " ..." LOGGER.debug("Compiling: %s", tmpl_s) try: if content is None: render_opts = anyconfig.utils.filter_options(RENDER_OPTS, options) return render(filepath, **render_opts) render_s_opts = anyconfig.utils.filter_options(RENDER_S_OPTS, options) return render_s(content, **render_s_opts) except Exception as exc: LOGGER.warning("Failed to compile '%s'. It may not be a template.%s" "exc=%r", tmpl_s, os.linesep, exc) return None
python
def try_render(filepath=None, content=None, **options): """ Compile and render template and return the result as a string. :param filepath: Absolute or relative path to the template file :param content: Template content (str) :param options: Keyword options passed to :func:`render` defined above. :return: Compiled result (str) or None """ if filepath is None and content is None: raise ValueError("Either 'path' or 'content' must be some value!") tmpl_s = filepath or content[:10] + " ..." LOGGER.debug("Compiling: %s", tmpl_s) try: if content is None: render_opts = anyconfig.utils.filter_options(RENDER_OPTS, options) return render(filepath, **render_opts) render_s_opts = anyconfig.utils.filter_options(RENDER_S_OPTS, options) return render_s(content, **render_s_opts) except Exception as exc: LOGGER.warning("Failed to compile '%s'. It may not be a template.%s" "exc=%r", tmpl_s, os.linesep, exc) return None
Compile and render template and return the result as a string. :param filepath: Absolute or relative path to the template file :param content: Template content (str) :param options: Keyword options passed to :func:`render` defined above. :return: Compiled result (str) or None
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/template.py#L175-L198
ssato/python-anyconfig
src/anyconfig/backend/ini.py
_parse
def _parse(val_s, sep=_SEP): """ FIXME: May be too naive implementation. :param val_s: A string represents some value to parse :param sep: separator between values >>> _parse(r'"foo string"') 'foo string' >>> _parse("a, b, c") ['a', 'b', 'c'] >>> _parse("aaa") 'aaa' """ if (val_s.startswith('"') and val_s.endswith('"')) or \ (val_s.startswith("'") and val_s.endswith("'")): return val_s[1:-1] if sep in val_s: return [P.parse(x) for x in P.parse_list(val_s)] return P.parse(val_s)
python
def _parse(val_s, sep=_SEP): """ FIXME: May be too naive implementation. :param val_s: A string represents some value to parse :param sep: separator between values >>> _parse(r'"foo string"') 'foo string' >>> _parse("a, b, c") ['a', 'b', 'c'] >>> _parse("aaa") 'aaa' """ if (val_s.startswith('"') and val_s.endswith('"')) or \ (val_s.startswith("'") and val_s.endswith("'")): return val_s[1:-1] if sep in val_s: return [P.parse(x) for x in P.parse_list(val_s)] return P.parse(val_s)
FIXME: May be too naive implementation. :param val_s: A string represents some value to parse :param sep: separator between values >>> _parse(r'"foo string"') 'foo string' >>> _parse("a, b, c") ['a', 'b', 'c'] >>> _parse("aaa") 'aaa'
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/ini.py#L52-L72
ssato/python-anyconfig
src/anyconfig/backend/ini.py
_to_s
def _to_s(val, sep=", "): """Convert any to string. :param val: An object :param sep: separator between values >>> _to_s([1, 2, 3]) '1, 2, 3' >>> _to_s("aaa") 'aaa' """ if anyconfig.utils.is_iterable(val): return sep.join(str(x) for x in val) return str(val)
python
def _to_s(val, sep=", "): """Convert any to string. :param val: An object :param sep: separator between values >>> _to_s([1, 2, 3]) '1, 2, 3' >>> _to_s("aaa") 'aaa' """ if anyconfig.utils.is_iterable(val): return sep.join(str(x) for x in val) return str(val)
Convert any to string. :param val: An object :param sep: separator between values >>> _to_s([1, 2, 3]) '1, 2, 3' >>> _to_s("aaa") 'aaa'
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/ini.py#L75-L89
ssato/python-anyconfig
src/anyconfig/backend/ini.py
_parsed_items
def _parsed_items(items, sep=_SEP, **options): """ :param items: List of pairs, [(key, value)], or generator yields pairs :param sep: Seprator string :return: Generator to yield (key, value) pair of 'dic' """ parse = _parse if options.get("ac_parse_value") else anyconfig.utils.noop for key, val in items: yield (key, parse(val, sep))
python
def _parsed_items(items, sep=_SEP, **options): """ :param items: List of pairs, [(key, value)], or generator yields pairs :param sep: Seprator string :return: Generator to yield (key, value) pair of 'dic' """ parse = _parse if options.get("ac_parse_value") else anyconfig.utils.noop for key, val in items: yield (key, parse(val, sep))
:param items: List of pairs, [(key, value)], or generator yields pairs :param sep: Seprator string :return: Generator to yield (key, value) pair of 'dic'
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/ini.py#L92-L100
ssato/python-anyconfig
src/anyconfig/backend/ini.py
_make_parser
def _make_parser(**kwargs): """ :return: (keyword args to be used, parser object) """ # Optional arguements for configparser.SafeConfigParser{,readfp} kwargs_0 = filter_options(("defaults", "dict_type", "allow_no_value"), kwargs) kwargs_1 = filter_options(("filename", ), kwargs) try: parser = configparser.SafeConfigParser(**kwargs_0) except TypeError: # .. note:: # It seems ConfigParser.*ConfigParser in python 2.6 does not support # 'allow_no_value' option parameter, and TypeError will be thrown. kwargs_0 = filter_options(("defaults", "dict_type"), kwargs) parser = configparser.SafeConfigParser(**kwargs_0) return (kwargs_1, parser)
python
def _make_parser(**kwargs): """ :return: (keyword args to be used, parser object) """ # Optional arguements for configparser.SafeConfigParser{,readfp} kwargs_0 = filter_options(("defaults", "dict_type", "allow_no_value"), kwargs) kwargs_1 = filter_options(("filename", ), kwargs) try: parser = configparser.SafeConfigParser(**kwargs_0) except TypeError: # .. note:: # It seems ConfigParser.*ConfigParser in python 2.6 does not support # 'allow_no_value' option parameter, and TypeError will be thrown. kwargs_0 = filter_options(("defaults", "dict_type"), kwargs) parser = configparser.SafeConfigParser(**kwargs_0) return (kwargs_1, parser)
:return: (keyword args to be used, parser object)
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/ini.py#L103-L121
ssato/python-anyconfig
src/anyconfig/backend/ini.py
_load
def _load(stream, container, sep=_SEP, dkey=DEFAULTSECT, **kwargs): """ :param stream: File or file-like object provides ini-style conf :param container: any callable to make container :param sep: Seprator string :param dkey: Default section name :return: Dict or dict-like object represents config values """ (kwargs_1, psr) = _make_parser(**kwargs) if IS_PYTHON_3: psr.read_file(stream, **kwargs_1) else: psr.readfp(stream, **kwargs_1) cnf = container() kwargs["sep"] = sep defaults = psr.defaults() if defaults: cnf[dkey] = container(_parsed_items(iteritems(defaults), **kwargs)) for sect in psr.sections(): cnf[sect] = container(_parsed_items(psr.items(sect), **kwargs)) return cnf
python
def _load(stream, container, sep=_SEP, dkey=DEFAULTSECT, **kwargs): """ :param stream: File or file-like object provides ini-style conf :param container: any callable to make container :param sep: Seprator string :param dkey: Default section name :return: Dict or dict-like object represents config values """ (kwargs_1, psr) = _make_parser(**kwargs) if IS_PYTHON_3: psr.read_file(stream, **kwargs_1) else: psr.readfp(stream, **kwargs_1) cnf = container() kwargs["sep"] = sep defaults = psr.defaults() if defaults: cnf[dkey] = container(_parsed_items(iteritems(defaults), **kwargs)) for sect in psr.sections(): cnf[sect] = container(_parsed_items(psr.items(sect), **kwargs)) return cnf
:param stream: File or file-like object provides ini-style conf :param container: any callable to make container :param sep: Seprator string :param dkey: Default section name :return: Dict or dict-like object represents config values
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/ini.py#L124-L149
ssato/python-anyconfig
src/anyconfig/backend/ini.py
_dumps_itr
def _dumps_itr(cnf, dkey=DEFAULTSECT): """ :param cnf: Configuration data to dump """ for sect, params in iteritems(cnf): yield "[%s]" % sect for key, val in iteritems(params): if sect != dkey and dkey in cnf and cnf[dkey].get(key) == val: continue # It should be in [DEFAULT] section. yield "%s = %s" % (key, _to_s(val)) yield ''
python
def _dumps_itr(cnf, dkey=DEFAULTSECT): """ :param cnf: Configuration data to dump """ for sect, params in iteritems(cnf): yield "[%s]" % sect for key, val in iteritems(params): if sect != dkey and dkey in cnf and cnf[dkey].get(key) == val: continue # It should be in [DEFAULT] section. yield "%s = %s" % (key, _to_s(val)) yield ''
:param cnf: Configuration data to dump
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/ini.py#L152-L165
ssato/python-anyconfig
src/anyconfig/backend/ini.py
_dumps
def _dumps(cnf, **kwargs): """ :param cnf: Configuration data to dump :param kwargs: optional keyword parameters to be sanitized :: dict :return: String representation of 'cnf' object in INI format """ return os.linesep.join(l for l in _dumps_itr(cnf))
python
def _dumps(cnf, **kwargs): """ :param cnf: Configuration data to dump :param kwargs: optional keyword parameters to be sanitized :: dict :return: String representation of 'cnf' object in INI format """ return os.linesep.join(l for l in _dumps_itr(cnf))
:param cnf: Configuration data to dump :param kwargs: optional keyword parameters to be sanitized :: dict :return: String representation of 'cnf' object in INI format
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/ini.py#L168-L175
ssato/python-anyconfig
src/anyconfig/query.py
query
def query(data, **options): """ Filter data with given JMESPath expression. See also: https://github.com/jmespath/jmespath.py and http://jmespath.org. :param data: Target object (a dict or a dict-like object) to query :param options: Keyword option may include 'ac_query' which is a string represents JMESPath expression. :return: Maybe queried result data, primitive (int, str, ...) or dict """ expression = options.get("ac_query", None) if expression is None or not expression: return data try: pexp = jmespath.compile(expression) return pexp.search(data) except ValueError as exc: # jmespath.exceptions.*Error inherit from it. LOGGER.warning("Failed to compile or search: exp=%s, exc=%r", expression, exc) except (NameError, AttributeError): LOGGER.warning("Filter module (jmespath) is not available. " "Do nothing.") return data
python
def query(data, **options): """ Filter data with given JMESPath expression. See also: https://github.com/jmespath/jmespath.py and http://jmespath.org. :param data: Target object (a dict or a dict-like object) to query :param options: Keyword option may include 'ac_query' which is a string represents JMESPath expression. :return: Maybe queried result data, primitive (int, str, ...) or dict """ expression = options.get("ac_query", None) if expression is None or not expression: return data try: pexp = jmespath.compile(expression) return pexp.search(data) except ValueError as exc: # jmespath.exceptions.*Error inherit from it. LOGGER.warning("Failed to compile or search: exp=%s, exc=%r", expression, exc) except (NameError, AttributeError): LOGGER.warning("Filter module (jmespath) is not available. " "Do nothing.") return data
Filter data with given JMESPath expression. See also: https://github.com/jmespath/jmespath.py and http://jmespath.org. :param data: Target object (a dict or a dict-like object) to query :param options: Keyword option may include 'ac_query' which is a string represents JMESPath expression. :return: Maybe queried result data, primitive (int, str, ...) or dict
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/query.py#L22-L49
ssato/python-anyconfig
src/anyconfig/utils.py
groupby
def groupby(itr, key_fn=None): """ An wrapper function around itertools.groupby to sort each results. :param itr: Iterable object, a list/tuple/genrator, etc. :param key_fn: Key function to sort 'itr'. >>> import operator >>> itr = [("a", 1), ("b", -1), ("c", 1)] >>> res = groupby(itr, operator.itemgetter(1)) >>> [(key, tuple(grp)) for key, grp in res] [(-1, (('b', -1),)), (1, (('a', 1), ('c', 1)))] """ return itertools.groupby(sorted(itr, key=key_fn), key=key_fn)
python
def groupby(itr, key_fn=None): """ An wrapper function around itertools.groupby to sort each results. :param itr: Iterable object, a list/tuple/genrator, etc. :param key_fn: Key function to sort 'itr'. >>> import operator >>> itr = [("a", 1), ("b", -1), ("c", 1)] >>> res = groupby(itr, operator.itemgetter(1)) >>> [(key, tuple(grp)) for key, grp in res] [(-1, (('b', -1),)), (1, (('a', 1), ('c', 1)))] """ return itertools.groupby(sorted(itr, key=key_fn), key=key_fn)
An wrapper function around itertools.groupby to sort each results. :param itr: Iterable object, a list/tuple/genrator, etc. :param key_fn: Key function to sort 'itr'. >>> import operator >>> itr = [("a", 1), ("b", -1), ("c", 1)] >>> res = groupby(itr, operator.itemgetter(1)) >>> [(key, tuple(grp)) for key, grp in res] [(-1, (('b', -1),)), (1, (('a', 1), ('c', 1)))]
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/utils.py#L22-L35
ssato/python-anyconfig
src/anyconfig/utils.py
get_file_extension
def get_file_extension(file_path): """ >>> get_file_extension("/a/b/c") '' >>> get_file_extension("/a/b.txt") 'txt' >>> get_file_extension("/a/b/c.tar.xz") 'xz' """ _ext = os.path.splitext(file_path)[-1] if _ext: return _ext[1:] if _ext.startswith('.') else _ext return ""
python
def get_file_extension(file_path): """ >>> get_file_extension("/a/b/c") '' >>> get_file_extension("/a/b.txt") 'txt' >>> get_file_extension("/a/b/c.tar.xz") 'xz' """ _ext = os.path.splitext(file_path)[-1] if _ext: return _ext[1:] if _ext.startswith('.') else _ext return ""
>>> get_file_extension("/a/b/c") '' >>> get_file_extension("/a/b.txt") 'txt' >>> get_file_extension("/a/b/c.tar.xz") 'xz'
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/utils.py#L38-L51
ssato/python-anyconfig
src/anyconfig/utils.py
is_iterable
def is_iterable(obj): """ >>> is_iterable([]) True >>> is_iterable(()) True >>> is_iterable([x for x in range(10)]) True >>> is_iterable((1, 2, 3)) True >>> g = (x for x in range(10)) >>> is_iterable(g) True >>> is_iterable("abc") False >>> is_iterable(0) False >>> is_iterable({}) False """ return isinstance(obj, (list, tuple, types.GeneratorType)) or \ (not isinstance(obj, (int, str, dict)) and bool(getattr(obj, "next", False)))
python
def is_iterable(obj): """ >>> is_iterable([]) True >>> is_iterable(()) True >>> is_iterable([x for x in range(10)]) True >>> is_iterable((1, 2, 3)) True >>> g = (x for x in range(10)) >>> is_iterable(g) True >>> is_iterable("abc") False >>> is_iterable(0) False >>> is_iterable({}) False """ return isinstance(obj, (list, tuple, types.GeneratorType)) or \ (not isinstance(obj, (int, str, dict)) and bool(getattr(obj, "next", False)))
>>> is_iterable([]) True >>> is_iterable(()) True >>> is_iterable([x for x in range(10)]) True >>> is_iterable((1, 2, 3)) True >>> g = (x for x in range(10)) >>> is_iterable(g) True >>> is_iterable("abc") False >>> is_iterable(0) False >>> is_iterable({}) False
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/utils.py#L61-L83
ssato/python-anyconfig
src/anyconfig/utils.py
is_ioinfo
def is_ioinfo(obj, keys=None): """ :return: True if given 'obj' is a 'IOInfo' namedtuple object. >>> assert not is_ioinfo(1) >>> assert not is_ioinfo("aaa") >>> assert not is_ioinfo({}) >>> assert not is_ioinfo(('a', 1, {})) >>> inp = anyconfig.globals.IOInfo("/etc/hosts", "path", "/etc/hosts", ... None, open) >>> assert is_ioinfo(inp) """ if keys is None: keys = anyconfig.globals.IOI_KEYS if isinstance(obj, tuple) and getattr(obj, "_asdict", False): return all(k in obj._asdict() for k in keys) return False
python
def is_ioinfo(obj, keys=None): """ :return: True if given 'obj' is a 'IOInfo' namedtuple object. >>> assert not is_ioinfo(1) >>> assert not is_ioinfo("aaa") >>> assert not is_ioinfo({}) >>> assert not is_ioinfo(('a', 1, {})) >>> inp = anyconfig.globals.IOInfo("/etc/hosts", "path", "/etc/hosts", ... None, open) >>> assert is_ioinfo(inp) """ if keys is None: keys = anyconfig.globals.IOI_KEYS if isinstance(obj, tuple) and getattr(obj, "_asdict", False): return all(k in obj._asdict() for k in keys) return False
:return: True if given 'obj' is a 'IOInfo' namedtuple object. >>> assert not is_ioinfo(1) >>> assert not is_ioinfo("aaa") >>> assert not is_ioinfo({}) >>> assert not is_ioinfo(('a', 1, {})) >>> inp = anyconfig.globals.IOInfo("/etc/hosts", "path", "/etc/hosts", ... None, open) >>> assert is_ioinfo(inp)
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/utils.py#L157-L176
ssato/python-anyconfig
src/anyconfig/utils.py
is_path_like_object
def is_path_like_object(obj, marker='*'): """ Is given object 'obj' a path string, a pathlib.Path, a file / file-like (stream) or IOInfo namedtuple object? :param obj: a path string, pathlib.Path object, a file / file-like or 'IOInfo' object :return: True if 'obj' is a path string or a pathlib.Path object or a file (stream) object >>> assert is_path_like_object(__file__) >>> assert not is_path_like_object("/a/b/c/*.json", '*') >>> from anyconfig.compat import pathlib >>> if pathlib is not None: ... assert is_path_like_object(pathlib.Path("a.ini")) ... assert not is_path_like_object(pathlib.Path("x.ini"), 'x') >>> assert is_path_like_object(open(__file__)) """ return ((is_path(obj) and marker not in obj) or (is_path_obj(obj) and marker not in obj.as_posix()) or is_file_stream(obj) or is_ioinfo(obj))
python
def is_path_like_object(obj, marker='*'): """ Is given object 'obj' a path string, a pathlib.Path, a file / file-like (stream) or IOInfo namedtuple object? :param obj: a path string, pathlib.Path object, a file / file-like or 'IOInfo' object :return: True if 'obj' is a path string or a pathlib.Path object or a file (stream) object >>> assert is_path_like_object(__file__) >>> assert not is_path_like_object("/a/b/c/*.json", '*') >>> from anyconfig.compat import pathlib >>> if pathlib is not None: ... assert is_path_like_object(pathlib.Path("a.ini")) ... assert not is_path_like_object(pathlib.Path("x.ini"), 'x') >>> assert is_path_like_object(open(__file__)) """ return ((is_path(obj) and marker not in obj) or (is_path_obj(obj) and marker not in obj.as_posix()) or is_file_stream(obj) or is_ioinfo(obj))
Is given object 'obj' a path string, a pathlib.Path, a file / file-like (stream) or IOInfo namedtuple object? :param obj: a path string, pathlib.Path object, a file / file-like or 'IOInfo' object :return: True if 'obj' is a path string or a pathlib.Path object or a file (stream) object >>> assert is_path_like_object(__file__) >>> assert not is_path_like_object("/a/b/c/*.json", '*') >>> from anyconfig.compat import pathlib >>> if pathlib is not None: ... assert is_path_like_object(pathlib.Path("a.ini")) ... assert not is_path_like_object(pathlib.Path("x.ini"), 'x') >>> assert is_path_like_object(open(__file__))
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/utils.py#L192-L217
ssato/python-anyconfig
src/anyconfig/utils.py
is_paths
def is_paths(maybe_paths, marker='*'): """ Does given object 'maybe_paths' consist of path or path pattern strings? """ return ((is_path(maybe_paths) and marker in maybe_paths) or # Path str (is_path_obj(maybe_paths) and marker in maybe_paths.as_posix()) or (is_iterable(maybe_paths) and all(is_path(p) or is_ioinfo(p) for p in maybe_paths)))
python
def is_paths(maybe_paths, marker='*'): """ Does given object 'maybe_paths' consist of path or path pattern strings? """ return ((is_path(maybe_paths) and marker in maybe_paths) or # Path str (is_path_obj(maybe_paths) and marker in maybe_paths.as_posix()) or (is_iterable(maybe_paths) and all(is_path(p) or is_ioinfo(p) for p in maybe_paths)))
Does given object 'maybe_paths' consist of path or path pattern strings?
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/utils.py#L220-L227
ssato/python-anyconfig
src/anyconfig/utils.py
get_path_from_stream
def get_path_from_stream(strm): """ Try to get file path from given file or file-like object 'strm'. :param strm: A file or file-like object :return: Path of given file or file-like object or None :raises: ValueError >>> assert __file__ == get_path_from_stream(open(__file__, 'r')) >>> assert get_path_from_stream(anyconfig.compat.StringIO()) is None >>> get_path_from_stream(__file__) # doctest: +ELLIPSIS Traceback (most recent call last): ... ValueError: ... """ if not is_file_stream(strm): raise ValueError("Given object does not look a file/file-like " "object: %r" % strm) path = getattr(strm, "name", None) if path is not None: try: return normpath(path) except (TypeError, ValueError): pass return None
python
def get_path_from_stream(strm): """ Try to get file path from given file or file-like object 'strm'. :param strm: A file or file-like object :return: Path of given file or file-like object or None :raises: ValueError >>> assert __file__ == get_path_from_stream(open(__file__, 'r')) >>> assert get_path_from_stream(anyconfig.compat.StringIO()) is None >>> get_path_from_stream(__file__) # doctest: +ELLIPSIS Traceback (most recent call last): ... ValueError: ... """ if not is_file_stream(strm): raise ValueError("Given object does not look a file/file-like " "object: %r" % strm) path = getattr(strm, "name", None) if path is not None: try: return normpath(path) except (TypeError, ValueError): pass return None
Try to get file path from given file or file-like object 'strm'. :param strm: A file or file-like object :return: Path of given file or file-like object or None :raises: ValueError >>> assert __file__ == get_path_from_stream(open(__file__, 'r')) >>> assert get_path_from_stream(anyconfig.compat.StringIO()) is None >>> get_path_from_stream(__file__) # doctest: +ELLIPSIS Traceback (most recent call last): ... ValueError: ...
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/utils.py#L230-L256
ssato/python-anyconfig
src/anyconfig/utils.py
_try_to_get_extension
def _try_to_get_extension(obj): """ Try to get file extension from given path or file object. :param obj: a file, file-like object or something :return: File extension or None >>> _try_to_get_extension("a.py") 'py' """ if is_path(obj): path = obj elif is_path_obj(obj): return obj.suffix[1:] elif is_file_stream(obj): try: path = get_path_from_stream(obj) except ValueError: return None elif is_ioinfo(obj): path = obj.path else: return None if path: return get_file_extension(path) return None
python
def _try_to_get_extension(obj): """ Try to get file extension from given path or file object. :param obj: a file, file-like object or something :return: File extension or None >>> _try_to_get_extension("a.py") 'py' """ if is_path(obj): path = obj elif is_path_obj(obj): return obj.suffix[1:] elif is_file_stream(obj): try: path = get_path_from_stream(obj) except ValueError: return None elif is_ioinfo(obj): path = obj.path else: return None if path: return get_file_extension(path) return None
Try to get file extension from given path or file object. :param obj: a file, file-like object or something :return: File extension or None >>> _try_to_get_extension("a.py") 'py'
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/utils.py#L259-L290
ssato/python-anyconfig
src/anyconfig/utils.py
are_same_file_types
def are_same_file_types(objs): """ Are given (maybe) file objs same type (extension) ? :param objs: A list of file path or file(-like) objects >>> are_same_file_types([]) False >>> are_same_file_types(["a.conf"]) True >>> are_same_file_types(["a.conf", "b.conf"]) True >>> are_same_file_types(["a.yml", "b.yml"]) True >>> are_same_file_types(["a.yml", "b.json"]) False >>> strm = anyconfig.compat.StringIO() >>> are_same_file_types(["a.yml", "b.yml", strm]) False """ if not objs: return False ext = _try_to_get_extension(objs[0]) if ext is None: return False return all(_try_to_get_extension(p) == ext for p in objs[1:])
python
def are_same_file_types(objs): """ Are given (maybe) file objs same type (extension) ? :param objs: A list of file path or file(-like) objects >>> are_same_file_types([]) False >>> are_same_file_types(["a.conf"]) True >>> are_same_file_types(["a.conf", "b.conf"]) True >>> are_same_file_types(["a.yml", "b.yml"]) True >>> are_same_file_types(["a.yml", "b.json"]) False >>> strm = anyconfig.compat.StringIO() >>> are_same_file_types(["a.yml", "b.yml", strm]) False """ if not objs: return False ext = _try_to_get_extension(objs[0]) if ext is None: return False return all(_try_to_get_extension(p) == ext for p in objs[1:])
Are given (maybe) file objs same type (extension) ? :param objs: A list of file path or file(-like) objects >>> are_same_file_types([]) False >>> are_same_file_types(["a.conf"]) True >>> are_same_file_types(["a.conf", "b.conf"]) True >>> are_same_file_types(["a.yml", "b.yml"]) True >>> are_same_file_types(["a.yml", "b.json"]) False >>> strm = anyconfig.compat.StringIO() >>> are_same_file_types(["a.yml", "b.yml", strm]) False
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/utils.py#L293-L320
ssato/python-anyconfig
src/anyconfig/utils.py
_expand_paths_itr
def _expand_paths_itr(paths, marker='*'): """Iterator version of :func:`expand_paths`. """ for path in paths: if is_path(path): if marker in path: # glob path pattern for ppath in sglob(path): yield ppath else: yield path # a simple file path elif is_path_obj(path): if marker in path.as_posix(): for ppath in sglob(path.as_posix()): yield normpath(ppath) else: yield normpath(path.as_posix()) elif is_ioinfo(path): yield path.path else: # A file or file-like object yield path
python
def _expand_paths_itr(paths, marker='*'): """Iterator version of :func:`expand_paths`. """ for path in paths: if is_path(path): if marker in path: # glob path pattern for ppath in sglob(path): yield ppath else: yield path # a simple file path elif is_path_obj(path): if marker in path.as_posix(): for ppath in sglob(path.as_posix()): yield normpath(ppath) else: yield normpath(path.as_posix()) elif is_ioinfo(path): yield path.path else: # A file or file-like object yield path
Iterator version of :func:`expand_paths`.
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/utils.py#L323-L342
ssato/python-anyconfig
src/anyconfig/utils.py
expand_paths
def expand_paths(paths, marker='*'): """ :param paths: A glob path pattern string or pathlib.Path object holding such path, or a list consists of path strings or glob path pattern strings or pathlib.Path object holding such ones, or file objects :param marker: Glob marker character or string, e.g. '*' :return: List of path strings >>> expand_paths([]) [] >>> expand_paths("/usr/lib/a/b.conf /etc/a/b.conf /run/a/b.conf".split()) ['/usr/lib/a/b.conf', '/etc/a/b.conf', '/run/a/b.conf'] >>> paths_s = os.path.join(os.path.dirname(__file__), "u*.py") >>> ref = sglob(paths_s) >>> assert expand_paths(paths_s) == ref >>> ref = ["/etc/a.conf"] + ref >>> assert expand_paths(["/etc/a.conf", paths_s]) == ref >>> strm = anyconfig.compat.StringIO() >>> assert expand_paths(["/etc/a.conf", strm]) == ["/etc/a.conf", strm] """ if is_path(paths) and marker in paths: return sglob(paths) if is_path_obj(paths) and marker in paths.as_posix(): # TBD: Is it better to return [p :: pathlib.Path] instead? return [normpath(p) for p in sglob(paths.as_posix())] return list(_expand_paths_itr(paths, marker=marker))
python
def expand_paths(paths, marker='*'): """ :param paths: A glob path pattern string or pathlib.Path object holding such path, or a list consists of path strings or glob path pattern strings or pathlib.Path object holding such ones, or file objects :param marker: Glob marker character or string, e.g. '*' :return: List of path strings >>> expand_paths([]) [] >>> expand_paths("/usr/lib/a/b.conf /etc/a/b.conf /run/a/b.conf".split()) ['/usr/lib/a/b.conf', '/etc/a/b.conf', '/run/a/b.conf'] >>> paths_s = os.path.join(os.path.dirname(__file__), "u*.py") >>> ref = sglob(paths_s) >>> assert expand_paths(paths_s) == ref >>> ref = ["/etc/a.conf"] + ref >>> assert expand_paths(["/etc/a.conf", paths_s]) == ref >>> strm = anyconfig.compat.StringIO() >>> assert expand_paths(["/etc/a.conf", strm]) == ["/etc/a.conf", strm] """ if is_path(paths) and marker in paths: return sglob(paths) if is_path_obj(paths) and marker in paths.as_posix(): # TBD: Is it better to return [p :: pathlib.Path] instead? return [normpath(p) for p in sglob(paths.as_posix())] return list(_expand_paths_itr(paths, marker=marker))
:param paths: A glob path pattern string or pathlib.Path object holding such path, or a list consists of path strings or glob path pattern strings or pathlib.Path object holding such ones, or file objects :param marker: Glob marker character or string, e.g. '*' :return: List of path strings >>> expand_paths([]) [] >>> expand_paths("/usr/lib/a/b.conf /etc/a/b.conf /run/a/b.conf".split()) ['/usr/lib/a/b.conf', '/etc/a/b.conf', '/run/a/b.conf'] >>> paths_s = os.path.join(os.path.dirname(__file__), "u*.py") >>> ref = sglob(paths_s) >>> assert expand_paths(paths_s) == ref >>> ref = ["/etc/a.conf"] + ref >>> assert expand_paths(["/etc/a.conf", paths_s]) == ref >>> strm = anyconfig.compat.StringIO() >>> assert expand_paths(["/etc/a.conf", strm]) == ["/etc/a.conf", strm]
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/utils.py#L345-L374
ssato/python-anyconfig
src/anyconfig/utils.py
is_list_like
def is_list_like(obj): """ >>> is_list_like([]) True >>> is_list_like(()) True >>> is_list_like([x for x in range(10)]) True >>> is_list_like((1, 2, 3)) True >>> g = (x for x in range(10)) >>> is_list_like(g) True >>> is_list_like("abc") False >>> is_list_like(0) False >>> is_list_like({}) False """ return isinstance(obj, _LIST_LIKE_TYPES) and \ not (isinstance(obj, anyconfig.compat.STR_TYPES) or is_dict_like(obj))
python
def is_list_like(obj): """ >>> is_list_like([]) True >>> is_list_like(()) True >>> is_list_like([x for x in range(10)]) True >>> is_list_like((1, 2, 3)) True >>> g = (x for x in range(10)) >>> is_list_like(g) True >>> is_list_like("abc") False >>> is_list_like(0) False >>> is_list_like({}) False """ return isinstance(obj, _LIST_LIKE_TYPES) and \ not (isinstance(obj, anyconfig.compat.STR_TYPES) or is_dict_like(obj))
>>> is_list_like([]) True >>> is_list_like(()) True >>> is_list_like([x for x in range(10)]) True >>> is_list_like((1, 2, 3)) True >>> g = (x for x in range(10)) >>> is_list_like(g) True >>> is_list_like("abc") False >>> is_list_like(0) False >>> is_list_like({}) False
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/utils.py#L417-L438
ssato/python-anyconfig
src/anyconfig/utils.py
filter_options
def filter_options(keys, options): """ Filter 'options' with given 'keys'. :param keys: key names of optional keyword arguments :param options: optional keyword arguments to filter with 'keys' >>> filter_options(("aaa", ), dict(aaa=1, bbb=2)) {'aaa': 1} >>> filter_options(("aaa", ), dict(bbb=2)) {} """ return dict((k, options[k]) for k in keys if k in options)
python
def filter_options(keys, options): """ Filter 'options' with given 'keys'. :param keys: key names of optional keyword arguments :param options: optional keyword arguments to filter with 'keys' >>> filter_options(("aaa", ), dict(aaa=1, bbb=2)) {'aaa': 1} >>> filter_options(("aaa", ), dict(bbb=2)) {} """ return dict((k, options[k]) for k in keys if k in options)
Filter 'options' with given 'keys'. :param keys: key names of optional keyword arguments :param options: optional keyword arguments to filter with 'keys' >>> filter_options(("aaa", ), dict(aaa=1, bbb=2)) {'aaa': 1} >>> filter_options(("aaa", ), dict(bbb=2)) {}
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/utils.py#L441-L453
ssato/python-anyconfig
src/anyconfig/utils.py
memoize
def memoize(fnc): """memoization function. >>> import random >>> imax = 100 >>> def fnc1(arg=True): ... return arg and random.choice((True, False)) >>> fnc2 = memoize(fnc1) >>> (ret1, ret2) = (fnc1(), fnc2()) >>> assert any(fnc1() != ret1 for i in range(imax)) >>> assert all(fnc2() == ret2 for i in range(imax)) """ cache = dict() @functools.wraps(fnc) def wrapped(*args, **kwargs): """Decorated one""" key = repr(args) + repr(kwargs) if key not in cache: cache[key] = fnc(*args, **kwargs) return cache[key] return wrapped
python
def memoize(fnc): """memoization function. >>> import random >>> imax = 100 >>> def fnc1(arg=True): ... return arg and random.choice((True, False)) >>> fnc2 = memoize(fnc1) >>> (ret1, ret2) = (fnc1(), fnc2()) >>> assert any(fnc1() != ret1 for i in range(imax)) >>> assert all(fnc2() == ret2 for i in range(imax)) """ cache = dict() @functools.wraps(fnc) def wrapped(*args, **kwargs): """Decorated one""" key = repr(args) + repr(kwargs) if key not in cache: cache[key] = fnc(*args, **kwargs) return cache[key] return wrapped
memoization function. >>> import random >>> imax = 100 >>> def fnc1(arg=True): ... return arg and random.choice((True, False)) >>> fnc2 = memoize(fnc1) >>> (ret1, ret2) = (fnc1(), fnc2()) >>> assert any(fnc1() != ret1 for i in range(imax)) >>> assert all(fnc2() == ret2 for i in range(imax))
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/utils.py#L456-L479
ssato/python-anyconfig
src/anyconfig/api.py
_try_validate
def _try_validate(cnf, schema, **options): """ :param cnf: Mapping object represents configuration data :param schema: JSON schema object :param options: Keyword options passed to :func:`jsonschema.validate` :return: Given 'cnf' as it is if validation succeeds else None """ valid = True if schema: (valid, msg) = validate(cnf, schema, **options) if msg: LOGGER.warning(msg) if valid: return cnf return None
python
def _try_validate(cnf, schema, **options): """ :param cnf: Mapping object represents configuration data :param schema: JSON schema object :param options: Keyword options passed to :func:`jsonschema.validate` :return: Given 'cnf' as it is if validation succeeds else None """ valid = True if schema: (valid, msg) = validate(cnf, schema, **options) if msg: LOGGER.warning(msg) if valid: return cnf return None
:param cnf: Mapping object represents configuration data :param schema: JSON schema object :param options: Keyword options passed to :func:`jsonschema.validate` :return: Given 'cnf' as it is if validation succeeds else None
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/api.py#L145-L162
ssato/python-anyconfig
src/anyconfig/api.py
_maybe_schema
def _maybe_schema(**options): """ :param options: Optional keyword arguments such as - ac_template: Assume configuration file may be a template file and try to compile it AAR if True - ac_context: Mapping object presents context to instantiate template - ac_schema: JSON schema file path to validate configuration files :return: Mapping object or None means some errors """ ac_schema = options.get("ac_schema", None) if ac_schema is not None: # Try to detect the appropriate parser to load the schema data as it # may be different from the original config file's format, perhaps. options["ac_parser"] = None options["ac_schema"] = None # Avoid infinite loop. LOGGER.info("Loading schema: %s", ac_schema) return load(ac_schema, **options) return None
python
def _maybe_schema(**options): """ :param options: Optional keyword arguments such as - ac_template: Assume configuration file may be a template file and try to compile it AAR if True - ac_context: Mapping object presents context to instantiate template - ac_schema: JSON schema file path to validate configuration files :return: Mapping object or None means some errors """ ac_schema = options.get("ac_schema", None) if ac_schema is not None: # Try to detect the appropriate parser to load the schema data as it # may be different from the original config file's format, perhaps. options["ac_parser"] = None options["ac_schema"] = None # Avoid infinite loop. LOGGER.info("Loading schema: %s", ac_schema) return load(ac_schema, **options) return None
:param options: Optional keyword arguments such as - ac_template: Assume configuration file may be a template file and try to compile it AAR if True - ac_context: Mapping object presents context to instantiate template - ac_schema: JSON schema file path to validate configuration files :return: Mapping object or None means some errors
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/api.py#L199-L219
ssato/python-anyconfig
src/anyconfig/api.py
open
def open(path, mode=None, ac_parser=None, **options): """ Open given configuration file with appropriate open flag. :param path: Configuration file path :param mode: Can be 'r' and 'rb' for reading (default) or 'w', 'wb' for writing. Please note that even if you specify 'r' or 'w', it will be changed to 'rb' or 'wb' if selected backend, xml and configobj for example, for given config file prefer that. :param options: Optional keyword arguments passed to the internal file opening APIs of each backends such like 'buffering' optional parameter passed to builtin 'open' function. :return: A file object or None on any errors :raises: ValueError, UnknownProcessorTypeError, UnknownFileTypeError """ psr = find(path, forced_type=ac_parser) if mode is not None and mode.startswith('w'): return psr.wopen(path, **options) return psr.ropen(path, **options)
python
def open(path, mode=None, ac_parser=None, **options): """ Open given configuration file with appropriate open flag. :param path: Configuration file path :param mode: Can be 'r' and 'rb' for reading (default) or 'w', 'wb' for writing. Please note that even if you specify 'r' or 'w', it will be changed to 'rb' or 'wb' if selected backend, xml and configobj for example, for given config file prefer that. :param options: Optional keyword arguments passed to the internal file opening APIs of each backends such like 'buffering' optional parameter passed to builtin 'open' function. :return: A file object or None on any errors :raises: ValueError, UnknownProcessorTypeError, UnknownFileTypeError """ psr = find(path, forced_type=ac_parser) if mode is not None and mode.startswith('w'): return psr.wopen(path, **options) return psr.ropen(path, **options)
Open given configuration file with appropriate open flag. :param path: Configuration file path :param mode: Can be 'r' and 'rb' for reading (default) or 'w', 'wb' for writing. Please note that even if you specify 'r' or 'w', it will be changed to 'rb' or 'wb' if selected backend, xml and configobj for example, for given config file prefer that. :param options: Optional keyword arguments passed to the internal file opening APIs of each backends such like 'buffering' optional parameter passed to builtin 'open' function. :return: A file object or None on any errors :raises: ValueError, UnknownProcessorTypeError, UnknownFileTypeError
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/api.py#L223-L246
ssato/python-anyconfig
src/anyconfig/api.py
_single_load
def _single_load(input_, ac_parser=None, ac_template=False, ac_context=None, **options): """ :param input_: File path or file or file-like object or pathlib.Path object represents the file or a namedtuple 'anyconfig.globals.IOInfo' object represents some input to load some data from :param ac_parser: Forced parser type or parser object itself :param ac_template: Assume configuration file may be a template file and try to compile it AAR if True :param ac_context: A dict presents context to instantiate template :param options: Optional keyword arguments :func:`single_load` supports except for ac_schema and ac_query :return: Mapping object :raises: ValueError, UnknownProcessorTypeError, UnknownFileTypeError """ ioi = anyconfig.ioinfo.make(input_) psr = find(ioi, forced_type=ac_parser) filepath = ioi.path # .. note:: # This will be kept for backward compatibility until 'ignore_missing' # option is deprecated and removed completely. if "ignore_missing" in options: warnings.warn("keyword option 'ignore_missing' is deprecated, use " "'ac_ignore_missing' instead", DeprecationWarning) options["ac_ignore_missing"] = options["ignore_missing"] LOGGER.info("Loading: %s", filepath) if ac_template and filepath is not None: content = anyconfig.template.try_render(filepath=filepath, ctx=ac_context, **options) if content is not None: return psr.loads(content, **options) return psr.load(ioi, **options)
python
def _single_load(input_, ac_parser=None, ac_template=False, ac_context=None, **options): """ :param input_: File path or file or file-like object or pathlib.Path object represents the file or a namedtuple 'anyconfig.globals.IOInfo' object represents some input to load some data from :param ac_parser: Forced parser type or parser object itself :param ac_template: Assume configuration file may be a template file and try to compile it AAR if True :param ac_context: A dict presents context to instantiate template :param options: Optional keyword arguments :func:`single_load` supports except for ac_schema and ac_query :return: Mapping object :raises: ValueError, UnknownProcessorTypeError, UnknownFileTypeError """ ioi = anyconfig.ioinfo.make(input_) psr = find(ioi, forced_type=ac_parser) filepath = ioi.path # .. note:: # This will be kept for backward compatibility until 'ignore_missing' # option is deprecated and removed completely. if "ignore_missing" in options: warnings.warn("keyword option 'ignore_missing' is deprecated, use " "'ac_ignore_missing' instead", DeprecationWarning) options["ac_ignore_missing"] = options["ignore_missing"] LOGGER.info("Loading: %s", filepath) if ac_template and filepath is not None: content = anyconfig.template.try_render(filepath=filepath, ctx=ac_context, **options) if content is not None: return psr.loads(content, **options) return psr.load(ioi, **options)
:param input_: File path or file or file-like object or pathlib.Path object represents the file or a namedtuple 'anyconfig.globals.IOInfo' object represents some input to load some data from :param ac_parser: Forced parser type or parser object itself :param ac_template: Assume configuration file may be a template file and try to compile it AAR if True :param ac_context: A dict presents context to instantiate template :param options: Optional keyword arguments :func:`single_load` supports except for ac_schema and ac_query :return: Mapping object :raises: ValueError, UnknownProcessorTypeError, UnknownFileTypeError
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/api.py#L249-L287
ssato/python-anyconfig
src/anyconfig/api.py
single_load
def single_load(input_, ac_parser=None, ac_template=False, ac_context=None, **options): r""" Load single configuration file. .. note:: :func:`load` is a preferable alternative and this API should be used only if there is a need to emphasize given input 'input\_' is single one. :param input\_: File path or file or file-like object or pathlib.Path object represents the file or a namedtuple 'anyconfig.globals.IOInfo' object represents some input to load some data from :param ac_parser: Forced parser type or parser object itself :param ac_template: Assume configuration file may be a template file and try to compile it AAR if True :param ac_context: A dict presents context to instantiate template :param options: Optional keyword arguments such as: - Options common in :func:`single_load`, :func:`multi_load`, :func:`load` and :func:`loads`: - ac_dict: callable (function or class) to make mapping objects from loaded data if the selected backend can customize that such as JSON which supports that with 'object_pairs_hook' option, or None. If this option was not given or None, dict or :class:`collections.OrderedDict` will be used to make result as mapping object depends on if ac_ordered (see below) is True and selected backend can keep the order of items loaded. See also :meth:`_container_factory` of :class:`anyconfig.backend.base.Parser` for more implementation details. - ac_ordered: True if you want to keep resuls ordered. Please note that order of items may be lost depends on the selected backend. - ac_schema: JSON schema file path to validate given config file - ac_query: JMESPath expression to query data - Common backend options: - ac_ignore_missing: Ignore and just return empty result if given file 'input\_' does not exist actually. - Backend specific options such as {"indent": 2} for JSON backend :return: Mapping object :raises: ValueError, UnknownProcessorTypeError, UnknownFileTypeError """ cnf = _single_load(input_, ac_parser=ac_parser, ac_template=ac_template, ac_context=ac_context, **options) schema = _maybe_schema(ac_template=ac_template, ac_context=ac_context, **options) cnf = _try_validate(cnf, schema, **options) return anyconfig.query.query(cnf, **options)
python
def single_load(input_, ac_parser=None, ac_template=False, ac_context=None, **options): r""" Load single configuration file. .. note:: :func:`load` is a preferable alternative and this API should be used only if there is a need to emphasize given input 'input\_' is single one. :param input\_: File path or file or file-like object or pathlib.Path object represents the file or a namedtuple 'anyconfig.globals.IOInfo' object represents some input to load some data from :param ac_parser: Forced parser type or parser object itself :param ac_template: Assume configuration file may be a template file and try to compile it AAR if True :param ac_context: A dict presents context to instantiate template :param options: Optional keyword arguments such as: - Options common in :func:`single_load`, :func:`multi_load`, :func:`load` and :func:`loads`: - ac_dict: callable (function or class) to make mapping objects from loaded data if the selected backend can customize that such as JSON which supports that with 'object_pairs_hook' option, or None. If this option was not given or None, dict or :class:`collections.OrderedDict` will be used to make result as mapping object depends on if ac_ordered (see below) is True and selected backend can keep the order of items loaded. See also :meth:`_container_factory` of :class:`anyconfig.backend.base.Parser` for more implementation details. - ac_ordered: True if you want to keep resuls ordered. Please note that order of items may be lost depends on the selected backend. - ac_schema: JSON schema file path to validate given config file - ac_query: JMESPath expression to query data - Common backend options: - ac_ignore_missing: Ignore and just return empty result if given file 'input\_' does not exist actually. - Backend specific options such as {"indent": 2} for JSON backend :return: Mapping object :raises: ValueError, UnknownProcessorTypeError, UnknownFileTypeError """ cnf = _single_load(input_, ac_parser=ac_parser, ac_template=ac_template, ac_context=ac_context, **options) schema = _maybe_schema(ac_template=ac_template, ac_context=ac_context, **options) cnf = _try_validate(cnf, schema, **options) return anyconfig.query.query(cnf, **options)
r""" Load single configuration file. .. note:: :func:`load` is a preferable alternative and this API should be used only if there is a need to emphasize given input 'input\_' is single one. :param input\_: File path or file or file-like object or pathlib.Path object represents the file or a namedtuple 'anyconfig.globals.IOInfo' object represents some input to load some data from :param ac_parser: Forced parser type or parser object itself :param ac_template: Assume configuration file may be a template file and try to compile it AAR if True :param ac_context: A dict presents context to instantiate template :param options: Optional keyword arguments such as: - Options common in :func:`single_load`, :func:`multi_load`, :func:`load` and :func:`loads`: - ac_dict: callable (function or class) to make mapping objects from loaded data if the selected backend can customize that such as JSON which supports that with 'object_pairs_hook' option, or None. If this option was not given or None, dict or :class:`collections.OrderedDict` will be used to make result as mapping object depends on if ac_ordered (see below) is True and selected backend can keep the order of items loaded. See also :meth:`_container_factory` of :class:`anyconfig.backend.base.Parser` for more implementation details. - ac_ordered: True if you want to keep resuls ordered. Please note that order of items may be lost depends on the selected backend. - ac_schema: JSON schema file path to validate given config file - ac_query: JMESPath expression to query data - Common backend options: - ac_ignore_missing: Ignore and just return empty result if given file 'input\_' does not exist actually. - Backend specific options such as {"indent": 2} for JSON backend :return: Mapping object :raises: ValueError, UnknownProcessorTypeError, UnknownFileTypeError
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/api.py#L290-L348
ssato/python-anyconfig
src/anyconfig/api.py
multi_load
def multi_load(inputs, ac_parser=None, ac_template=False, ac_context=None, **options): r""" Load multiple config files. .. note:: :func:`load` is a preferable alternative and this API should be used only if there is a need to emphasize given inputs are multiple ones. The first argument 'inputs' may be a list of a file paths or a glob pattern specifying them or a pathlib.Path object represents file[s] or a namedtuple 'anyconfig.globals.IOInfo' object represents some inputs to load some data from. About glob patterns, for example, is, if a.yml, b.yml and c.yml are in the dir /etc/foo/conf.d/, the followings give same results:: multi_load(["/etc/foo/conf.d/a.yml", "/etc/foo/conf.d/b.yml", "/etc/foo/conf.d/c.yml", ]) multi_load("/etc/foo/conf.d/*.yml") :param inputs: A list of file path or a glob pattern such as r'/a/b/\*.json'to list of files, file or file-like object or pathlib.Path object represents the file or a namedtuple 'anyconfig.globals.IOInfo' object represents some inputs to load some data from :param ac_parser: Forced parser type or parser object :param ac_template: Assume configuration file may be a template file and try to compile it AAR if True :param ac_context: Mapping object presents context to instantiate template :param options: Optional keyword arguments: - ac_dict, ac_ordered, ac_schema and ac_query are the options common in :func:`single_load`, :func:`multi_load`, :func:`load`: and :func:`loads`. See the descriptions of them in :func:`single_load`. - Options specific to this function and :func:`load`: - ac_merge (merge): Specify strategy of how to merge results loaded from multiple configuration files. See the doc of :mod:`anyconfig.dicts` for more details of strategies. The default is anyconfig.dicts.MS_DICTS. - ac_marker (marker): Globbing marker to detect paths patterns. - Common backend options: - ignore_missing: Ignore and just return empty result if given file 'path' does not exist. - Backend specific options such as {"indent": 2} for JSON backend :return: Mapping object or any query result might be primitive objects :raises: ValueError, UnknownProcessorTypeError, UnknownFileTypeError """ marker = options.setdefault("ac_marker", options.get("marker", '*')) schema = _maybe_schema(ac_template=ac_template, ac_context=ac_context, **options) options["ac_schema"] = None # Avoid to load schema more than twice. paths = anyconfig.utils.expand_paths(inputs, marker=marker) if anyconfig.utils.are_same_file_types(paths): ac_parser = find(paths[0], forced_type=ac_parser) cnf = ac_context for path in paths: opts = options.copy() cups = _single_load(path, ac_parser=ac_parser, ac_template=ac_template, ac_context=cnf, **opts) if cups: if cnf is None: cnf = cups else: merge(cnf, cups, **options) if cnf is None: return anyconfig.dicts.convert_to({}, **options) cnf = _try_validate(cnf, schema, **options) return anyconfig.query.query(cnf, **options)
python
def multi_load(inputs, ac_parser=None, ac_template=False, ac_context=None, **options): r""" Load multiple config files. .. note:: :func:`load` is a preferable alternative and this API should be used only if there is a need to emphasize given inputs are multiple ones. The first argument 'inputs' may be a list of a file paths or a glob pattern specifying them or a pathlib.Path object represents file[s] or a namedtuple 'anyconfig.globals.IOInfo' object represents some inputs to load some data from. About glob patterns, for example, is, if a.yml, b.yml and c.yml are in the dir /etc/foo/conf.d/, the followings give same results:: multi_load(["/etc/foo/conf.d/a.yml", "/etc/foo/conf.d/b.yml", "/etc/foo/conf.d/c.yml", ]) multi_load("/etc/foo/conf.d/*.yml") :param inputs: A list of file path or a glob pattern such as r'/a/b/\*.json'to list of files, file or file-like object or pathlib.Path object represents the file or a namedtuple 'anyconfig.globals.IOInfo' object represents some inputs to load some data from :param ac_parser: Forced parser type or parser object :param ac_template: Assume configuration file may be a template file and try to compile it AAR if True :param ac_context: Mapping object presents context to instantiate template :param options: Optional keyword arguments: - ac_dict, ac_ordered, ac_schema and ac_query are the options common in :func:`single_load`, :func:`multi_load`, :func:`load`: and :func:`loads`. See the descriptions of them in :func:`single_load`. - Options specific to this function and :func:`load`: - ac_merge (merge): Specify strategy of how to merge results loaded from multiple configuration files. See the doc of :mod:`anyconfig.dicts` for more details of strategies. The default is anyconfig.dicts.MS_DICTS. - ac_marker (marker): Globbing marker to detect paths patterns. - Common backend options: - ignore_missing: Ignore and just return empty result if given file 'path' does not exist. - Backend specific options such as {"indent": 2} for JSON backend :return: Mapping object or any query result might be primitive objects :raises: ValueError, UnknownProcessorTypeError, UnknownFileTypeError """ marker = options.setdefault("ac_marker", options.get("marker", '*')) schema = _maybe_schema(ac_template=ac_template, ac_context=ac_context, **options) options["ac_schema"] = None # Avoid to load schema more than twice. paths = anyconfig.utils.expand_paths(inputs, marker=marker) if anyconfig.utils.are_same_file_types(paths): ac_parser = find(paths[0], forced_type=ac_parser) cnf = ac_context for path in paths: opts = options.copy() cups = _single_load(path, ac_parser=ac_parser, ac_template=ac_template, ac_context=cnf, **opts) if cups: if cnf is None: cnf = cups else: merge(cnf, cups, **options) if cnf is None: return anyconfig.dicts.convert_to({}, **options) cnf = _try_validate(cnf, schema, **options) return anyconfig.query.query(cnf, **options)
r""" Load multiple config files. .. note:: :func:`load` is a preferable alternative and this API should be used only if there is a need to emphasize given inputs are multiple ones. The first argument 'inputs' may be a list of a file paths or a glob pattern specifying them or a pathlib.Path object represents file[s] or a namedtuple 'anyconfig.globals.IOInfo' object represents some inputs to load some data from. About glob patterns, for example, is, if a.yml, b.yml and c.yml are in the dir /etc/foo/conf.d/, the followings give same results:: multi_load(["/etc/foo/conf.d/a.yml", "/etc/foo/conf.d/b.yml", "/etc/foo/conf.d/c.yml", ]) multi_load("/etc/foo/conf.d/*.yml") :param inputs: A list of file path or a glob pattern such as r'/a/b/\*.json'to list of files, file or file-like object or pathlib.Path object represents the file or a namedtuple 'anyconfig.globals.IOInfo' object represents some inputs to load some data from :param ac_parser: Forced parser type or parser object :param ac_template: Assume configuration file may be a template file and try to compile it AAR if True :param ac_context: Mapping object presents context to instantiate template :param options: Optional keyword arguments: - ac_dict, ac_ordered, ac_schema and ac_query are the options common in :func:`single_load`, :func:`multi_load`, :func:`load`: and :func:`loads`. See the descriptions of them in :func:`single_load`. - Options specific to this function and :func:`load`: - ac_merge (merge): Specify strategy of how to merge results loaded from multiple configuration files. See the doc of :mod:`anyconfig.dicts` for more details of strategies. The default is anyconfig.dicts.MS_DICTS. - ac_marker (marker): Globbing marker to detect paths patterns. - Common backend options: - ignore_missing: Ignore and just return empty result if given file 'path' does not exist. - Backend specific options such as {"indent": 2} for JSON backend :return: Mapping object or any query result might be primitive objects :raises: ValueError, UnknownProcessorTypeError, UnknownFileTypeError
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/api.py#L351-L432
ssato/python-anyconfig
src/anyconfig/api.py
load
def load(path_specs, ac_parser=None, ac_dict=None, ac_template=False, ac_context=None, **options): r""" Load single or multiple config files or multiple config files specified in given paths pattern or pathlib.Path object represents config files or a namedtuple 'anyconfig.globals.IOInfo' object represents some inputs. :param path_specs: A list of file path or a glob pattern such as r'/a/b/\*.json'to list of files, file or file-like object or pathlib.Path object represents the file or a namedtuple 'anyconfig.globals.IOInfo' object represents some inputs to load some data from. :param ac_parser: Forced parser type or parser object :param ac_dict: callable (function or class) to make mapping object will be returned as a result or None. If not given or ac_dict is None, default mapping object used to store resutls is dict or :class:`collections.OrderedDict` if ac_ordered is True and selected backend can keep the order of items in mapping objects. :param ac_template: Assume configuration file may be a template file and try to compile it AAR if True :param ac_context: A dict presents context to instantiate template :param options: Optional keyword arguments. See also the description of 'options' in :func:`single_load` and :func:`multi_load` :return: Mapping object or any query result might be primitive objects :raises: ValueError, UnknownProcessorTypeError, UnknownFileTypeError """ marker = options.setdefault("ac_marker", options.get("marker", '*')) if anyconfig.utils.is_path_like_object(path_specs, marker): return single_load(path_specs, ac_parser=ac_parser, ac_dict=ac_dict, ac_template=ac_template, ac_context=ac_context, **options) if not anyconfig.utils.is_paths(path_specs, marker): raise ValueError("Possible invalid input %r" % path_specs) return multi_load(path_specs, ac_parser=ac_parser, ac_dict=ac_dict, ac_template=ac_template, ac_context=ac_context, **options)
python
def load(path_specs, ac_parser=None, ac_dict=None, ac_template=False, ac_context=None, **options): r""" Load single or multiple config files or multiple config files specified in given paths pattern or pathlib.Path object represents config files or a namedtuple 'anyconfig.globals.IOInfo' object represents some inputs. :param path_specs: A list of file path or a glob pattern such as r'/a/b/\*.json'to list of files, file or file-like object or pathlib.Path object represents the file or a namedtuple 'anyconfig.globals.IOInfo' object represents some inputs to load some data from. :param ac_parser: Forced parser type or parser object :param ac_dict: callable (function or class) to make mapping object will be returned as a result or None. If not given or ac_dict is None, default mapping object used to store resutls is dict or :class:`collections.OrderedDict` if ac_ordered is True and selected backend can keep the order of items in mapping objects. :param ac_template: Assume configuration file may be a template file and try to compile it AAR if True :param ac_context: A dict presents context to instantiate template :param options: Optional keyword arguments. See also the description of 'options' in :func:`single_load` and :func:`multi_load` :return: Mapping object or any query result might be primitive objects :raises: ValueError, UnknownProcessorTypeError, UnknownFileTypeError """ marker = options.setdefault("ac_marker", options.get("marker", '*')) if anyconfig.utils.is_path_like_object(path_specs, marker): return single_load(path_specs, ac_parser=ac_parser, ac_dict=ac_dict, ac_template=ac_template, ac_context=ac_context, **options) if not anyconfig.utils.is_paths(path_specs, marker): raise ValueError("Possible invalid input %r" % path_specs) return multi_load(path_specs, ac_parser=ac_parser, ac_dict=ac_dict, ac_template=ac_template, ac_context=ac_context, **options)
r""" Load single or multiple config files or multiple config files specified in given paths pattern or pathlib.Path object represents config files or a namedtuple 'anyconfig.globals.IOInfo' object represents some inputs. :param path_specs: A list of file path or a glob pattern such as r'/a/b/\*.json'to list of files, file or file-like object or pathlib.Path object represents the file or a namedtuple 'anyconfig.globals.IOInfo' object represents some inputs to load some data from. :param ac_parser: Forced parser type or parser object :param ac_dict: callable (function or class) to make mapping object will be returned as a result or None. If not given or ac_dict is None, default mapping object used to store resutls is dict or :class:`collections.OrderedDict` if ac_ordered is True and selected backend can keep the order of items in mapping objects. :param ac_template: Assume configuration file may be a template file and try to compile it AAR if True :param ac_context: A dict presents context to instantiate template :param options: Optional keyword arguments. See also the description of 'options' in :func:`single_load` and :func:`multi_load` :return: Mapping object or any query result might be primitive objects :raises: ValueError, UnknownProcessorTypeError, UnknownFileTypeError
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/api.py#L435-L477
ssato/python-anyconfig
src/anyconfig/api.py
loads
def loads(content, ac_parser=None, ac_dict=None, ac_template=False, ac_context=None, **options): """ :param content: Configuration file's content (a string) :param ac_parser: Forced parser type or ID or parser object :param ac_dict: callable (function or class) to make mapping object will be returned as a result or None. If not given or ac_dict is None, default mapping object used to store resutls is dict or :class:`collections.OrderedDict` if ac_ordered is True and selected backend can keep the order of items in mapping objects. :param ac_template: Assume configuration file may be a template file and try to compile it AAR if True :param ac_context: Context dict to instantiate template :param options: Optional keyword arguments. See also the description of 'options' in :func:`single_load` function. :return: Mapping object or any query result might be primitive objects :raises: ValueError, UnknownProcessorTypeError """ if ac_parser is None: LOGGER.warning("ac_parser was not given but it's must to find correct " "parser to load configurations from string.") return None psr = find(None, forced_type=ac_parser) schema = None ac_schema = options.get("ac_schema", None) if ac_schema is not None: options["ac_schema"] = None schema = loads(ac_schema, ac_parser=psr, ac_dict=ac_dict, ac_template=ac_template, ac_context=ac_context, **options) if ac_template: compiled = anyconfig.template.try_render(content=content, ctx=ac_context, **options) if compiled is not None: content = compiled cnf = psr.loads(content, ac_dict=ac_dict, **options) cnf = _try_validate(cnf, schema, **options) return anyconfig.query.query(cnf, **options)
python
def loads(content, ac_parser=None, ac_dict=None, ac_template=False, ac_context=None, **options): """ :param content: Configuration file's content (a string) :param ac_parser: Forced parser type or ID or parser object :param ac_dict: callable (function or class) to make mapping object will be returned as a result or None. If not given or ac_dict is None, default mapping object used to store resutls is dict or :class:`collections.OrderedDict` if ac_ordered is True and selected backend can keep the order of items in mapping objects. :param ac_template: Assume configuration file may be a template file and try to compile it AAR if True :param ac_context: Context dict to instantiate template :param options: Optional keyword arguments. See also the description of 'options' in :func:`single_load` function. :return: Mapping object or any query result might be primitive objects :raises: ValueError, UnknownProcessorTypeError """ if ac_parser is None: LOGGER.warning("ac_parser was not given but it's must to find correct " "parser to load configurations from string.") return None psr = find(None, forced_type=ac_parser) schema = None ac_schema = options.get("ac_schema", None) if ac_schema is not None: options["ac_schema"] = None schema = loads(ac_schema, ac_parser=psr, ac_dict=ac_dict, ac_template=ac_template, ac_context=ac_context, **options) if ac_template: compiled = anyconfig.template.try_render(content=content, ctx=ac_context, **options) if compiled is not None: content = compiled cnf = psr.loads(content, ac_dict=ac_dict, **options) cnf = _try_validate(cnf, schema, **options) return anyconfig.query.query(cnf, **options)
:param content: Configuration file's content (a string) :param ac_parser: Forced parser type or ID or parser object :param ac_dict: callable (function or class) to make mapping object will be returned as a result or None. If not given or ac_dict is None, default mapping object used to store resutls is dict or :class:`collections.OrderedDict` if ac_ordered is True and selected backend can keep the order of items in mapping objects. :param ac_template: Assume configuration file may be a template file and try to compile it AAR if True :param ac_context: Context dict to instantiate template :param options: Optional keyword arguments. See also the description of 'options' in :func:`single_load` function. :return: Mapping object or any query result might be primitive objects :raises: ValueError, UnknownProcessorTypeError
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/api.py#L480-L523
ssato/python-anyconfig
src/anyconfig/api.py
dump
def dump(data, out, ac_parser=None, **options): """ Save 'data' to 'out'. :param data: A mapping object may have configurations data to dump :param out: An output file path, a file, a file-like object, :class:`pathlib.Path` object represents the file or a namedtuple 'anyconfig.globals.IOInfo' object represents output to dump some data to. :param ac_parser: Forced parser type or parser object :param options: Backend specific optional arguments, e.g. {"indent": 2} for JSON loader/dumper backend :raises: ValueError, UnknownProcessorTypeError, UnknownFileTypeError """ ioi = anyconfig.ioinfo.make(out) psr = find(ioi, forced_type=ac_parser) LOGGER.info("Dumping: %s", ioi.path) psr.dump(data, ioi, **options)
python
def dump(data, out, ac_parser=None, **options): """ Save 'data' to 'out'. :param data: A mapping object may have configurations data to dump :param out: An output file path, a file, a file-like object, :class:`pathlib.Path` object represents the file or a namedtuple 'anyconfig.globals.IOInfo' object represents output to dump some data to. :param ac_parser: Forced parser type or parser object :param options: Backend specific optional arguments, e.g. {"indent": 2} for JSON loader/dumper backend :raises: ValueError, UnknownProcessorTypeError, UnknownFileTypeError """ ioi = anyconfig.ioinfo.make(out) psr = find(ioi, forced_type=ac_parser) LOGGER.info("Dumping: %s", ioi.path) psr.dump(data, ioi, **options)
Save 'data' to 'out'. :param data: A mapping object may have configurations data to dump :param out: An output file path, a file, a file-like object, :class:`pathlib.Path` object represents the file or a namedtuple 'anyconfig.globals.IOInfo' object represents output to dump some data to. :param ac_parser: Forced parser type or parser object :param options: Backend specific optional arguments, e.g. {"indent": 2} for JSON loader/dumper backend :raises: ValueError, UnknownProcessorTypeError, UnknownFileTypeError
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/api.py#L526-L545
ssato/python-anyconfig
src/anyconfig/api.py
dumps
def dumps(data, ac_parser=None, **options): """ Return string representation of 'data' in forced type format. :param data: Config data object to dump :param ac_parser: Forced parser type or ID or parser object :param options: see :func:`dump` :return: Backend-specific string representation for the given data :raises: ValueError, UnknownProcessorTypeError """ psr = find(None, forced_type=ac_parser) return psr.dumps(data, **options)
python
def dumps(data, ac_parser=None, **options): """ Return string representation of 'data' in forced type format. :param data: Config data object to dump :param ac_parser: Forced parser type or ID or parser object :param options: see :func:`dump` :return: Backend-specific string representation for the given data :raises: ValueError, UnknownProcessorTypeError """ psr = find(None, forced_type=ac_parser) return psr.dumps(data, **options)
Return string representation of 'data' in forced type format. :param data: Config data object to dump :param ac_parser: Forced parser type or ID or parser object :param options: see :func:`dump` :return: Backend-specific string representation for the given data :raises: ValueError, UnknownProcessorTypeError
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/api.py#L548-L560
ssato/python-anyconfig
src/anyconfig/api.py
query
def query(data, expression, **options): """ API just wraps :func:`anyconfig.query.query`. :param data: Config data object to query :param expression: JMESPath expression to query data :param options: Ignored in current implementation :return: Query result object may be a primitive (int, str, etc.) or dict. """ return anyconfig.query.query(data, ac_query=expression)
python
def query(data, expression, **options): """ API just wraps :func:`anyconfig.query.query`. :param data: Config data object to query :param expression: JMESPath expression to query data :param options: Ignored in current implementation :return: Query result object may be a primitive (int, str, etc.) or dict. """ return anyconfig.query.query(data, ac_query=expression)
API just wraps :func:`anyconfig.query.query`. :param data: Config data object to query :param expression: JMESPath expression to query data :param options: Ignored in current implementation :return: Query result object may be a primitive (int, str, etc.) or dict.
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/api.py#L563-L573
ssato/python-anyconfig
src/anyconfig/init.py
getLogger
def getLogger(name="anyconfig"): """ See: "Configuring Logging for a Library" in python standard logging howto, e.g. https://docs.python.org/2/howto/logging.html#library-config. """ logger = logging.getLogger(name) logger.addHandler(anyconfig.compat.NullHandler()) return logger
python
def getLogger(name="anyconfig"): """ See: "Configuring Logging for a Library" in python standard logging howto, e.g. https://docs.python.org/2/howto/logging.html#library-config. """ logger = logging.getLogger(name) logger.addHandler(anyconfig.compat.NullHandler()) return logger
See: "Configuring Logging for a Library" in python standard logging howto, e.g. https://docs.python.org/2/howto/logging.html#library-config.
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/init.py#L13-L21
ssato/python-anyconfig
src/anyconfig/parser.py
parse_single
def parse_single(str_): """ Very simple parser to parse expressions represent some single values. :param str_: a string to parse :return: Int | Bool | String >>> parse_single(None) '' >>> parse_single("0") 0 >>> parse_single("123") 123 >>> parse_single("True") True >>> parse_single("a string") 'a string' >>> parse_single('"a string"') 'a string' >>> parse_single("'a string'") 'a string' >>> parse_single("0.1") '0.1' >>> parse_single(" a string contains extra whitespaces ") 'a string contains extra whitespaces' """ if str_ is None: return '' str_ = str_.strip() if not str_: return '' if BOOL_PATTERN.match(str_) is not None: return bool(str_) if INT_PATTERN.match(str_) is not None: return int(str_) if STR_PATTERN.match(str_) is not None: return str_[1:-1] return str_
python
def parse_single(str_): """ Very simple parser to parse expressions represent some single values. :param str_: a string to parse :return: Int | Bool | String >>> parse_single(None) '' >>> parse_single("0") 0 >>> parse_single("123") 123 >>> parse_single("True") True >>> parse_single("a string") 'a string' >>> parse_single('"a string"') 'a string' >>> parse_single("'a string'") 'a string' >>> parse_single("0.1") '0.1' >>> parse_single(" a string contains extra whitespaces ") 'a string contains extra whitespaces' """ if str_ is None: return '' str_ = str_.strip() if not str_: return '' if BOOL_PATTERN.match(str_) is not None: return bool(str_) if INT_PATTERN.match(str_) is not None: return int(str_) if STR_PATTERN.match(str_) is not None: return str_[1:-1] return str_
Very simple parser to parse expressions represent some single values. :param str_: a string to parse :return: Int | Bool | String >>> parse_single(None) '' >>> parse_single("0") 0 >>> parse_single("123") 123 >>> parse_single("True") True >>> parse_single("a string") 'a string' >>> parse_single('"a string"') 'a string' >>> parse_single("'a string'") 'a string' >>> parse_single("0.1") '0.1' >>> parse_single(" a string contains extra whitespaces ") 'a string contains extra whitespaces'
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/parser.py#L17-L60
ssato/python-anyconfig
src/anyconfig/parser.py
parse_list
def parse_list(str_, sep=","): """ Simple parser to parse expressions reprensent some list values. :param str_: a string to parse :param sep: Char to separate items of list :return: [Int | Bool | String] >>> parse_list("") [] >>> parse_list("1") [1] >>> parse_list("a,b") ['a', 'b'] >>> parse_list("1,2") [1, 2] >>> parse_list("a,b,") ['a', 'b'] """ return [parse_single(x) for x in str_.split(sep) if x]
python
def parse_list(str_, sep=","): """ Simple parser to parse expressions reprensent some list values. :param str_: a string to parse :param sep: Char to separate items of list :return: [Int | Bool | String] >>> parse_list("") [] >>> parse_list("1") [1] >>> parse_list("a,b") ['a', 'b'] >>> parse_list("1,2") [1, 2] >>> parse_list("a,b,") ['a', 'b'] """ return [parse_single(x) for x in str_.split(sep) if x]
Simple parser to parse expressions reprensent some list values. :param str_: a string to parse :param sep: Char to separate items of list :return: [Int | Bool | String] >>> parse_list("") [] >>> parse_list("1") [1] >>> parse_list("a,b") ['a', 'b'] >>> parse_list("1,2") [1, 2] >>> parse_list("a,b,") ['a', 'b']
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/parser.py#L63-L82
ssato/python-anyconfig
src/anyconfig/parser.py
attr_val_itr
def attr_val_itr(str_, avs_sep=":", vs_sep=",", as_sep=";"): """ Atrribute and value pair parser. :param str_: String represents a list of pairs of attribute and value :param avs_sep: char to separate attribute and values :param vs_sep: char to separate values :param as_sep: char to separate attributes """ for rel in parse_list(str_, as_sep): if avs_sep not in rel or rel.endswith(avs_sep): continue (_attr, _values) = parse_list(rel, avs_sep) if vs_sep in str(_values): _values = parse_list(_values, vs_sep) if _values: yield (_attr, _values)
python
def attr_val_itr(str_, avs_sep=":", vs_sep=",", as_sep=";"): """ Atrribute and value pair parser. :param str_: String represents a list of pairs of attribute and value :param avs_sep: char to separate attribute and values :param vs_sep: char to separate values :param as_sep: char to separate attributes """ for rel in parse_list(str_, as_sep): if avs_sep not in rel or rel.endswith(avs_sep): continue (_attr, _values) = parse_list(rel, avs_sep) if vs_sep in str(_values): _values = parse_list(_values, vs_sep) if _values: yield (_attr, _values)
Atrribute and value pair parser. :param str_: String represents a list of pairs of attribute and value :param avs_sep: char to separate attribute and values :param vs_sep: char to separate values :param as_sep: char to separate attributes
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/parser.py#L85-L104
ssato/python-anyconfig
src/anyconfig/parser.py
parse_attrlist_0
def parse_attrlist_0(str_, avs_sep=":", vs_sep=",", as_sep=";"): """ Simple parser to parse expressions in the form of [ATTR1:VAL0,VAL1,...;ATTR2:VAL0,VAL2,..]. :param str_: input string :param avs_sep: char to separate attribute and values :param vs_sep: char to separate values :param as_sep: char to separate attributes :return: a list of tuples of (key, value | [value]) where key = (Int | String | ...), value = (Int | Bool | String | ...) | [Int | Bool | String | ...] >>> parse_attrlist_0("a:1") [('a', 1)] >>> parse_attrlist_0("a:1;b:xyz") [('a', 1), ('b', 'xyz')] >>> parse_attrlist_0("requires:bash,zsh") [('requires', ['bash', 'zsh'])] >>> parse_attrlist_0("obsoletes:sysdata;conflicts:sysdata-old") [('obsoletes', 'sysdata'), ('conflicts', 'sysdata-old')] """ return [(a, vs) for a, vs in attr_val_itr(str_, avs_sep, vs_sep, as_sep)]
python
def parse_attrlist_0(str_, avs_sep=":", vs_sep=",", as_sep=";"): """ Simple parser to parse expressions in the form of [ATTR1:VAL0,VAL1,...;ATTR2:VAL0,VAL2,..]. :param str_: input string :param avs_sep: char to separate attribute and values :param vs_sep: char to separate values :param as_sep: char to separate attributes :return: a list of tuples of (key, value | [value]) where key = (Int | String | ...), value = (Int | Bool | String | ...) | [Int | Bool | String | ...] >>> parse_attrlist_0("a:1") [('a', 1)] >>> parse_attrlist_0("a:1;b:xyz") [('a', 1), ('b', 'xyz')] >>> parse_attrlist_0("requires:bash,zsh") [('requires', ['bash', 'zsh'])] >>> parse_attrlist_0("obsoletes:sysdata;conflicts:sysdata-old") [('obsoletes', 'sysdata'), ('conflicts', 'sysdata-old')] """ return [(a, vs) for a, vs in attr_val_itr(str_, avs_sep, vs_sep, as_sep)]
Simple parser to parse expressions in the form of [ATTR1:VAL0,VAL1,...;ATTR2:VAL0,VAL2,..]. :param str_: input string :param avs_sep: char to separate attribute and values :param vs_sep: char to separate values :param as_sep: char to separate attributes :return: a list of tuples of (key, value | [value]) where key = (Int | String | ...), value = (Int | Bool | String | ...) | [Int | Bool | String | ...] >>> parse_attrlist_0("a:1") [('a', 1)] >>> parse_attrlist_0("a:1;b:xyz") [('a', 1), ('b', 'xyz')] >>> parse_attrlist_0("requires:bash,zsh") [('requires', ['bash', 'zsh'])] >>> parse_attrlist_0("obsoletes:sysdata;conflicts:sysdata-old") [('obsoletes', 'sysdata'), ('conflicts', 'sysdata-old')]
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/parser.py#L107-L131
ssato/python-anyconfig
src/anyconfig/parser.py
parse_attrlist
def parse_attrlist(str_, avs_sep=":", vs_sep=",", as_sep=";"): """ Simple parser to parse expressions in the form of [ATTR1:VAL0,VAL1,...;ATTR2:VAL0,VAL2,..]. :param str_: input string :param avs_sep: char to separate attribute and values :param vs_sep: char to separate values :param as_sep: char to separate attributes >>> parse_attrlist("requires:bash,zsh") {'requires': ['bash', 'zsh']} """ return dict(parse_attrlist_0(str_, avs_sep, vs_sep, as_sep))
python
def parse_attrlist(str_, avs_sep=":", vs_sep=",", as_sep=";"): """ Simple parser to parse expressions in the form of [ATTR1:VAL0,VAL1,...;ATTR2:VAL0,VAL2,..]. :param str_: input string :param avs_sep: char to separate attribute and values :param vs_sep: char to separate values :param as_sep: char to separate attributes >>> parse_attrlist("requires:bash,zsh") {'requires': ['bash', 'zsh']} """ return dict(parse_attrlist_0(str_, avs_sep, vs_sep, as_sep))
Simple parser to parse expressions in the form of [ATTR1:VAL0,VAL1,...;ATTR2:VAL0,VAL2,..]. :param str_: input string :param avs_sep: char to separate attribute and values :param vs_sep: char to separate values :param as_sep: char to separate attributes >>> parse_attrlist("requires:bash,zsh") {'requires': ['bash', 'zsh']}
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/parser.py#L134-L147
ssato/python-anyconfig
src/anyconfig/parser.py
parse
def parse(str_, lsep=",", avsep=":", vssep=",", avssep=";"): """Generic parser""" if avsep in str_: return parse_attrlist(str_, avsep, vssep, avssep) if lsep in str_: return parse_list(str_, lsep) return parse_single(str_)
python
def parse(str_, lsep=",", avsep=":", vssep=",", avssep=";"): """Generic parser""" if avsep in str_: return parse_attrlist(str_, avsep, vssep, avssep) if lsep in str_: return parse_list(str_, lsep) return parse_single(str_)
Generic parser
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/parser.py#L150-L157
ssato/python-anyconfig
src/anyconfig/cli.py
to_log_level
def to_log_level(level): """ :param level: Logging level in int = 0 .. 2 >>> to_log_level(0) == logging.WARN True >>> to_log_level(5) # doctest: +IGNORE_EXCEPTION_DETAIL, +ELLIPSIS Traceback (most recent call last): ... ValueError: wrong log level passed: 5 >>> """ if level < 0 or level >= 3: raise ValueError("wrong log level passed: " + str(level)) return [logging.WARN, logging.INFO, logging.DEBUG][level]
python
def to_log_level(level): """ :param level: Logging level in int = 0 .. 2 >>> to_log_level(0) == logging.WARN True >>> to_log_level(5) # doctest: +IGNORE_EXCEPTION_DETAIL, +ELLIPSIS Traceback (most recent call last): ... ValueError: wrong log level passed: 5 >>> """ if level < 0 or level >= 3: raise ValueError("wrong log level passed: " + str(level)) return [logging.WARN, logging.INFO, logging.DEBUG][level]
:param level: Logging level in int = 0 .. 2 >>> to_log_level(0) == logging.WARN True >>> to_log_level(5) # doctest: +IGNORE_EXCEPTION_DETAIL, +ELLIPSIS Traceback (most recent call last): ... ValueError: wrong log level passed: 5 >>>
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/cli.py#L74-L89