Home > Back-end >  Using OR in if statement to see if either query param present
Using OR in if statement to see if either query param present

Time:08-10

I am looking to implement a simple filter using a single query param (eg age=gt:40, name=eq:bob). I am wondering if it is possible to check if either name or age is present in the GET request at once? An example might clarify what I'm after:

if ('age' or 'name') in request.GET:

This will only match when the first one is used. When I hit the endpoint with the query param name it doesn't match true.

I know I could do something like:

if ('age' in request.GET) or ('name' in request.GET) :

but this could grow quite quickly and become ugly.

CodePudding user response:

You can use any(…) [Python-doc]:

if any(x in request.GET for x in ('age', 'name')):
    # …
    pass

CodePudding user response:

Another option is to use set intersection:

if {'age', 'name'}.intersection(request.GET)
    ...

It is slightly less efficient than any (no early stopping), but IMO it's more readable

  • Related