1

I'm doing a bunch of operations that are basically:

if ((x is not None) and (y is not None)) and x > y:
    do_something

I'm doing this operation on every row of a data table where some of the values are null. Is there a more pythonic way of going about this, without have to check for None each time?

Aloha Ray
  • 13
  • 4
  • 1
    I dont't see how this could be imporved. However if instead of `x` and `y` are going to use large expression you could split this condition into different if-conditions firstly checking for `None` and then comparing `x` and `y` – ktv6 May 08 '21 at 10:01
  • 1
    you do know where x and y come from right? then you also know if None check is needed or not – Serve Laurijssen May 08 '21 at 10:06
  • 1
    Perhaps: `if not None in (x, y) and x > y:`. This form can easily be extended to even more variables. – DarrylG May 08 '21 at 10:06
  • Take a look at this question https://stackoverflow.com/questions/42360956/what-is-the-most-pythonic-way-to-check-if-multiple-variables-are-not-none – ktv6 May 08 '21 at 10:11

3 Answers3

2

The parentheses are not needed, and None must be capitalized. Otherwise this is basically a good way to do it. Your data table might offer a way of filtering out all rows with None values at once, which would be an improvement.

nnnmmm
  • 7,964
  • 4
  • 22
  • 41
  • Thanks, I tend to over use parentheses in my conditionals, I'll streamline it a bit going forward though. – Aloha Ray May 08 '21 at 10:46
2

Perhaps:

if not None in (x, y) and x > y:
    do_something()
DarrylG
  • 16,732
  • 2
  • 17
  • 23
0

There is not a 'better' way to do it, however if you want to do it in one short line and make it more idiomatic, you could use:

do_something() if x is not None and y is not None and (x>y) else do_something_else()
Shivam Roy
  • 1,961
  • 3
  • 10
  • 23
  • @DarrylG thank you, I just learned a new thing that this code doesn't take zero inot account, edited the answer accordingly. Now it works for 0, -1 – Shivam Roy May 08 '21 at 10:27