text
stringlengths
0
828
Falls back to :class:`bool` when ``value`` is not recognized.
:param value: the value to convert
:returns: ``True`` if value is truthy, ``False`` otherwise
:rtype: bool
""""""
cases = {
'0': False,
'false': False,
'no': False,
'1': True,
'true': True,
'yes': True,
}
value = value.lower() if isinstance(value, basestring) else value
return cases.get(value, bool(value))"
4010,"def etree_to_dict(t, trim=True, **kw):
u""""""Converts an lxml.etree object to Python dict.
>>> etree_to_dict(etree.Element('root'))
{'root': None}
:param etree.Element t: lxml tree to convert
:returns d: a dict representing the lxml tree ``t``
:rtype: dict
""""""
d = {t.tag: {} if t.attrib else None}
children = list(t)
etree_to_dict_w_args = partial(etree_to_dict, trim=trim, **kw)
if children:
dd = defaultdict(list)
d = {t.tag: {}}
for dc in map(etree_to_dict_w_args, children):
for k, v in dc.iteritems():
# do not add Comment instance to the key
if k is not etree.Comment:
dd[k].append(v)
d[t.tag] = {k: v[0] if len(v) == 1 else v for k, v in dd.iteritems()}
if t.attrib:
d[t.tag].update(('@' + k, v) for k, v in t.attrib.iteritems())
if trim and t.text:
t.text = t.text.strip()
if t.text:
if t.tag is etree.Comment and not kw.get('without_comments'):
# adds a comments node
d['#comments'] = t.text
elif children or t.attrib:
d[t.tag]['#text'] = t.text
else:
d[t.tag] = t.text
return d"
4011,"def dict_to_etree(d, root):
u""""""Converts a dict to lxml.etree object.
>>> dict_to_etree({'root': {'#text': 'node_text', '@attr': 'val'}}, etree.Element('root')) # doctest: +ELLIPSIS
<Element root at 0x...>
:param dict d: dict representing the XML tree
:param etree.Element root: XML node which will be assigned the resulting tree
:returns: Textual representation of the XML tree
:rtype: str
""""""
def _to_etree(d, node):
if d is None or len(d) == 0:
return
elif isinstance(d, basestring):
node.text = d
elif isinstance(d, dict):
for k, v in d.items():
assert isinstance(k, basestring)
if k.startswith('#'):
assert k == '#text'
assert isinstance(v, basestring)
node.text = v
elif k.startswith('@'):
assert isinstance(v, basestring)
node.set(k[1:], v)
elif isinstance(v, list):
# No matter the child count, their parent will be the same.
sub_elem = etree.SubElement(node, k)
for child_num, e in enumerate(v):
if e is None:
if child_num == 0:
# Found the first occurrence of an empty child,
# skip creating of its XML repr, since it would be
# the same as ``sub_element`` higher up.
continue
# A list with None element means an empty child node
# in its parent, thus, recreating tags we have to go
# up one level.
# <node><child/></child></node> <=> {'node': 'child': [None, None]}
_to_etree(node, k)
else:
# If this isn't first child and it's a complex