3

The Python and and or operators, return values, rather than True or False, which is useful for things such as:

x = d.get(1) or d.get(2) or d.get(3)

Which will make x the value of d[1], d[2] or d[3] which ever is present. This is a bit like having an additive Maybe monad in functional languages.

I've always wanted that the python any() function would be more like a repeated or. I think it would make sense return the object it finds, like:

any([None, None, 1, 2, None]) == 1
any(notnull_iterator) = try: return next(notnull_iterator); except: return None

And likewise for all(). It seems to me the change would be entirely backwards compatible, and increase consistency across the API.

Does anyone know of a previous discussion of this topic?

Thomas Ahle
  • 30,774
  • 21
  • 92
  • 114
  • Actually, in your example - if `d[1]` is a Falsey value, it will process to `d[2]` etc. In that case, to be safe you could use `x = d.get(1, d.get(2, d.get(3)))` however, unfortunately that won't short circuit – John La Rooy Dec 05 '13 at 13:11
  • That's true, but often enough I find my data structures populated with my own objects, that are never `None`. – Thomas Ahle Dec 05 '13 at 14:35

2 Answers2

5

I guess you're looking for

first = lambda s: next((x for x in s if x), None)

e.g.

first([None, None,1, 2,None]) # 1

The "why" question is answered over here.

Community
  • 1
  • 1
georg
  • 211,518
  • 52
  • 313
  • 390
2
>>> from functools import partial
>>> my_any = partial(reduce, lambda x, y:x or y)
>>> my_any([None, None, 1, 2, None])
1

>>> my_all = partial(reduce, lambda x, y:x and y)
>>> my_all([0, 0, 1, 2, 0])
0

In the above example, my_all([]) raises an exception. However, you can easily provide a default value instead

>>> my_all([], "Foo")
'Foo'
John La Rooy
  • 295,403
  • 53
  • 369
  • 502
  • I know I can implement them myself. It's just that it would be nice functionality to have in the standard library, and it seems like it wouldn't make the api heavier. Maybe even lighten it. Though the all([]) case is a challenge. – Thomas Ahle Dec 05 '13 at 11:22
  • @ThomasAhle, well you can specify a default value in that case, so choose a True or False value that suits your needs. – John La Rooy Dec 05 '13 at 13:07