4

The following SQLAlchemy code works, but looks un-pythonic:

if has_died: # has_died: True or False
  query = query.filter(User.died_at != None)
else:
  query = query.filter(User.died_at == None)

What is a more elegant way to add the filter?

Thorben Croisé
  • 12,407
  • 8
  • 39
  • 50

3 Answers3

5

Well, you could do this:

query = query.filter((User.died_at != None) if has_died else (User.died_at == None))

But it's a bit hard to read. I think how you're doing it is fine.

Cyphase
  • 11,502
  • 2
  • 31
  • 32
3

You could rewrite it as one line with a ternary operator

query = query.filter((User.died_at != None) if has_died else (User.died_at == None))
SuperBiasedMan
  • 9,814
  • 10
  • 45
  • 73
0

What about:

query = query.filter(bool(User.died_at) == has_died)

It returns:

  • False if User.died_at is None and has_died is True
  • True if User.died_at is None and has_died is False
  • True if User.died_at is not None and has_died is True
  • False if User.died_at is not None and has_died is False

Which is the intended behavior...

But then again, not sure if it is easier to understand than your piece of code!

Challensois
  • 522
  • 2
  • 10
  • 1
    `User.died_at != None` and `User.died_at == None` don't return a `bool`; they return a SQLAlchemy object. As linked by [Yaroslav Admin](https://stackoverflow.com/users/1377864/yaroslav-admin) in the question comments: https://stackoverflow.com/questions/21784851/sqlalchemy-is-not-null-select/21784915#21784915 – Cyphase Aug 18 '15 at 12:05
  • Oh I am not familiar with SQLAlchemy syntax. Stricly speaking in python, a `None` is considered as `False`. Is there a way to make this call valid ? Because then I think it is the most elegant way to do it. Otherwise sorry for my faulty contribution. – Challensois Aug 18 '15 at 12:06
  • No problem. Even if it behaved closer to how you expected, while `bool(None) == False`, `None != False`, so they're not the same thing. You could have a value that could be `True`, `False`, or `None`, with each one having it's own meaning. For example, if it's the answer to a yes/no question, they might mean `Yes`, `No`, and `Unanswered`. – Cyphase Aug 18 '15 at 12:10
  • Indeed, my comment could be misleading, it is `bool(None)` that is considered as `False`. It is true that `None`, `False` and `True` all have different meanings. – Challensois Aug 18 '15 at 12:14