Pythonic way to convert XML attribute to float, or else get None My Python code is converting XML attributes in an 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 radius


I 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 &gt;= 0:
  # do stuff using radius


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 None to properly signify that no radius was passed.
It's a bit difficult to get 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 &gt;= 0 test would also continue to work.