title: Handling NoneType in len() while in a Python lambda expression?
body: <p>From what I understand, Python lambda's only allow expressions, not statements. I have a case where I an using <code>len()</code> in a lambda expression and am trying to get the length of the return value of a function call.  However, that function call has the potential to return <code>None</code>, which breaks <code>len()</code>.  Is there a graceful way around this?</p>
  
  <p>Example:</p>
  
  <pre><code>def foo(obj_list, field):
      return maxk(obj_list, key=lambda obj: len(nested_getattr(obj, field)))
  </code></pre>
  
  <p>In the above, <code>maxk()</code> is a version of <code>max()</code> that accepts a <code>key</code> argument.  I'm on Python 2.4 (and cannot use anything higher at present), so I have a custom implementation of <code>max()</code> that takes a key argument, sourced <a href="http://bytes.com/topic/python/answers/37337-key-argument-max" rel="nofollow">from here</a> (refer to posts #140122 and #140143).  <code>nested_getattr()</code> is another utility function that acts like <code>getattr()</code> but can fetch an attribute nested within another.  That can be sourced <a href="http://bytes.com/topic/python/answers/830134-getattr-nested-attributes#post3315464" rel="nofollow">from here</a>.</p>
  
  <p>What the example function does (this is the actual function I am using with variables/names changed) is go through a list of objects (<code>obj_list</code>) and compare the length of the value in <code>field</code> and returns the object in the list whose <code>field</code> is the largest overall.</p>
  
  <p>However, if the attribute specified in <code>field</code> for each object returns <code>None</code>, then <code>len()</code> will choke with a <code>TypeError</code>.  I think I could get around this using an inline conditional, but I would have to call <code>nested_getattr()</code> twice, once for the check, and possibly a second time if its return value is not <code>None</code>.  I would rather like to cache its return value to a variable and run that on a conditional before deciding what to return (or just have the generator expression skip over it entirely).</p>
  
  <p>What's a good way to handle this?  I am open to other implementations of this function, <code>maxk()</code>, or <code>nested_getattr()</code> (if need be).</p>