snippetpythonMinor
Pythonic way to convert XML attribute to float, or else get None
Viewed 0 times
pythonicelsenoneconvertfloatwayxmlgetattribute
Problem
My Python code is converting XML attributes in an
Best I have now is:
I dislike this because it's not DRY (repeats both
But (a) that only works when I know that a particular attribute value is otherwise invalid, and (b) it's not as "clean" to me as using
ElementTree to appropriate values. How do I best convert a value in this dict to a float() if it exists, or else get None?Best I have now is:
attr = etree_elem.attrib
self.radius = float(attr['radius']) if 'radius' in attr else None
...
if self.radius:
# do stuff using radiusI dislike this because it's not DRY (repeats both
'radius' and attr). I had code like this:self.radius = float(attr.get('radius', -1))
...
if self.radius >= 0:
# do stuff using radiusBut (a) that only works when I know that a particular attribute value is otherwise invalid, and (b) it's not as "clean" to me as using
None to properly signify that no radius was passed.Solution
It's a bit difficult to get
You can use
None without writing an explicit conditional. The next best option may be to go with float('nan') instead of -1 to make it harder to accidentally use it as a value.self.radius = float(etree_elem.attrib.get('radius', 'nan'))You can use
math.isfinite() to test the existence of a value. The self.radius >= 0 test would also continue to work.Code Snippets
self.radius = float(etree_elem.attrib.get('radius', 'nan'))Context
StackExchange Code Review Q#145109, answer score: 2
Revisions (0)
No revisions yet.