class DictFromTagsInString(dict):
Constructor: DictFromTagsInString(*args, **kwargs)
read from a string or file all key-value pairs within all
<python>...</python> tags and return a dict
.
Within the tags valid Python code is expected: either a list of key-value pairs [[key1, value1], [key2, value2], ...] or a dictionary { key1: value1, key2: value2, ...}. A key can be any immutable object, while it is often a string or a number.
The as_python_tag
attribute provides the respective (tagged) string.
The tag_string attribute defines the tag identifier, 'python' by
default, and can be change if desired at any time.
>>> from cma.utilities.utils import DictFromTagsInString >>> s = '<python> [[33, 44], ["annotations", [None, 2]]] </python>' >>> s += '<python> {"annotations": [2, 3]} </python>' >>> d = DictFromTagsInString(s) >>> # now d.update can be used to read more tagged strings/files/... >>> assert d.tag_string == 'python' # can be set to any other value >>> d.tag_string = 'pyt' >>> # now 'pyt' tags can/will be read (only) >>> assert str(d).startswith('<pyt>{') and str(d).endswith('}</pyt>') >>> assert len(d) == 2 and d[33] == 44 and d['annotations'] == [2, 3]
When the same key appears several times, its value is overwritten.
Method | __init__ |
for input args see update method. |
Method | __repr__ |
Undocumented |
Method | update |
only one of the first four arguments is accepted at a time, return self. |
Instance Variable | tag |
Undocumented |
Property | as |
Undocumented |
Method | _eval |
read [key, value] pairs from a list or a dict within all <self.tag_str> tags in str_ and return a dict . |
Property | _end |
Undocumented |
Property | _start |
Undocumented |
only one of the first four arguments is accepted at a time, return self.
If the first argument has no keyword, it is assumed to be a string to be parsed for tags.
read [key, value] pairs from a list
or a dict
within all
<self.tag_str> tags in str_ and return a dict
.
>>> from cma.utilities.utils import DictFromTagsInString >>> s = '<py> [[33, 44], ["annotations", []]] </py>' >>> s += '<py>[["annotations", [1,2,3]]] </py>' >>> d = DictFromTagsInString() >>> assert len(d) == 0 >>> d.update(s) # still empty as default tag is not <py> <python>{}</python> >>> assert len(d) == 0 >>> d.tag_string = "py" # set desired tag >>> d.update(s) # doctest:+ELLIPSIS <py>{... >>> assert len(d) == 2 >>> assert d[33] == 44 and len(d["annotations"]) == 3