An elegant way to filter by anyone or not.

The following SQLAlchemy code works, but looks non-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 a filter?

+4
source share
3 answers

Ok, you could do this:

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

But it is a little difficult to read. I think you are doing it fine.

+4
source

You can rewrite it as one line with a ternary operator

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

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 not None but has_died is True
  • False if User.died_at not None but has_died is False

What intentional behavior ...

But then again, I'm not sure if this is easier to understand than your piece of code!

0
source

All Articles