Jaideep Shekhar
Jaideep Shekhar

Reputation: 886

Python condition syntax irregularity

This is valid:

def not_none(some_variable) -> bool:
    return some_variable != None

And this is also valid:

def not_none(some_variable) -> bool:
    return some_variable is not None

Why is this invalid?

def not_none(some_variable) -> bool:
    return some_variable not None

I would think that it means the same as the previous one.
Is there any reason it is not allowed?

Upvotes: 0

Views: 47

Answers (2)

Carcigenicate
Carcigenicate

Reputation: 45806

not is a unary operator, it only accepts a single argument (whatever is on its right). Compare that with is not and != which are binary operators that each accept two arguments.

This is a problem because with just not, you essentially have

return (someVariable) (not None)

But that doesn't make sense. someVariable is just floating there before the call to not. It doesn't understand what you're intending, so you get an error.

Upvotes: 1

deceze
deceze

Reputation: 522442

There's a unary not (takes one operand and negates it), and an is not operator (optimised negation of is operator); however, there's no binary not operator (taking two operands).

Upvotes: 2

Related Questions