def none_aware(val, default): return default if val is None else val 

The library has a function that returns either a list or None, but I want to write

 return [HtmlParser(el) for el in none_aware(content.select('...'), [])] 

Instead of several lines of checks.

  • 2
    I did not understand the question. The function is ready for you, you showed its use, you do not need to write a few lines of checks. This code does not work or what is the essence of the question? Or do not you like the need for a function, and you want some kind of built-in design? - andreymal

3 answers 3

You can try this:

 return [HtmlParser(el) for el in (content.select('...') or [])] 

It is only necessary to take into account that the __bool__ method can be redefined by the __bool__ , but usually even in those rare cases when it is redefined, its behavior in logical expressions remains within the framework of the intuitively expected.

  • one
    map(HtmlParser, content.select('...') or []) if the list is not needed - jfs
  • since the function returns either a list or None, the or operator always works here (regardless of which objects are in the returned list) - jfs

If you are a fan of single-line code, here:

 >>> def f(v,d=1): return d if v is None else v ... >>> f(None) 1 

With python you can do this:

 >>> a = lambda x: x if x else None >>> a(None) >>> a(1) 1 >>> a([i for i in range(10)]) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> 

And if you call immediately:

 >>> (lambda x: x if x else None)([i for i in range(10)]) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 
     [HtmlParser(el) for el in content.select('...') or []] 

    or will return the first value that is True or the last value