1

Is there some kind of keyword to use in Python, that can be logically compared to always be false?

For example, I want something like

None > 20

To return false when evaluated. Is there some keyword to use besides None here, since comparing a NoneType and Integer throws an error?

2
  • Can you elaborate on what exactly you're trying to achieve with this. . .some context Commented Dec 7, 2016 at 15:43
  • @MosesKoledoye I have some logic that sets the value of a key in a dictionary to be None if some condition is met. Later, I am using eval to evaluate some boolean logic, which then goes and tries to compare None > 20 (or some other number). I actually got around this by putting eval in a try/except block, and passing the TypeError, but I'm not sure if that is the best way to do this. Commented Dec 7, 2016 at 15:46

1 Answer 1

6

I don't think there's a built-in object that does this, but you can always make your own:

class Thing:
    def __lt__(self, other):
        return False
    #use the same function for <=, ==, >, etc
    __le__ = __eq__ = __gt__ = __ge__ = __lt__

x = Thing()
print(x < 20)
print(x <= 20)
print(x > 20)
print(x >= 20)
print(x == 20)

Result:

False
False
False
False
False

Edit: I remembered a built-in way to do this. If you only need to compare to ordinary numbers, you can use the special "Not a Number" floating point value:

x = float("nan")
print(x < 20)
print(x <= 20)
print(x > 20)
print(x >= 20)
print(x == 20)

Result:

False
False
False
False
False

And if you specifically only want x > 20 to return False and don't particularly care what the other comparisons return, it may make more sense to use the special "negative infinity" floating point value.

>>> x = float("-inf")
>>> x > 20
False
Sign up to request clarification or add additional context in comments.

2 Comments

Does float("nan") also return false when used in an inequality operation? I need it to return false for float("nan") != 20
Let's see... Nope, float("nan") != 20 evaluates to True. Looks like you'll have to define your own type after all. (don't forget to add __ne__ to the __le__ = __eq__ = ... chain)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.