Skip to content

Commit

Permalink
Modernise some code in the ElementMaker implementation.
Browse files Browse the repository at this point in the history
  • Loading branch information
scoder committed Feb 14, 2022
1 parent ec2b2e5 commit 6210469
Showing 1 changed file with 11 additions and 21 deletions.
32 changes: 11 additions & 21 deletions src/lxml/builder.py
Expand Up @@ -148,34 +148,22 @@ def CLASS(v):

def __init__(self, typemap=None,
namespace=None, nsmap=None, makeelement=None):
if namespace is not None:
self._namespace = '{' + namespace + '}'
else:
self._namespace = None
self._namespace = '{' + namespace + '}' if namespace is not None else None
self._nsmap = dict(nsmap) if nsmap else None

if nsmap:
self._nsmap = dict(nsmap)
else:
self._nsmap = None
assert makeelement is None or callable(makeelement)
self._makeelement = makeelement if makeelement is not None else ET.Element

if makeelement is not None:
assert callable(makeelement)
self._makeelement = makeelement
else:
self._makeelement = ET.Element

# initialize type map for this element factory

if typemap:
typemap = dict(typemap)
else:
typemap = {}
# initialize the default type map functions for this element factory
typemap = dict(typemap) if typemap else {}

def add_text(elem, item):
try:
elem[-1].tail = (elem[-1].tail or "") + item
last_child = elem[-1]
except IndexError:
elem.text = (elem.text or "") + item
else:
last_child.tail = (last_child.tail or "") + item

def add_cdata(elem, cdata):
if elem.text:
Expand All @@ -196,6 +184,7 @@ def add_dict(elem, item):
attrib[k] = v
else:
attrib[k] = typemap[type(v)](None, v)

if dict not in typemap:
typemap[dict] = add_dict

Expand All @@ -204,6 +193,7 @@ def add_dict(elem, item):
def __call__(self, tag, *children, **attrib):
typemap = self._typemap

# We'll usually get a 'str', and the compiled type check is very fast.
if not isinstance(tag, str) and isinstance(tag, _QName):
# A QName is explicitly qualified, do not look at self._namespace.
tag = tag.text
Expand Down

0 comments on commit 6210469

Please sign in to comment.