Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing None with built-in types using arithmetic operators?

Python 2.7.2 (default, Jun 12 2011, 14:24:46) [MSC v.1500 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> None > 0 False >>> None == 0 False >>> None < 0 True 
  • Is comparing None using arithmetic operators well defined for built-in types (integers in this case)?
  • Is the difference between the first two and the third comparison part of language specification (Python's specification - you must be kidding :)) or is it CPython's implementation detail?
like image 379
Piotr Dobrogost Avatar asked Jan 22 '12 12:01

Piotr Dobrogost


People also ask

How do you compare with none?

Use the is operator to compare to None in Python, e.g. if my_var is None: . The is operator returns True if the two values point to the same object (it checks for identity), whereas the double equals == operator checks if the two values are equal.

Can none be compared with variables?

We can assign None to any variable, but you can not create other NoneType objects.

Is any number greater than none in Python?

None is always less than any datatype in Python 2 (see object. c ).

What is the use of operator in Python?

In Python, operators are special symbols that designate that some sort of computation should be performed. The values that an operator acts on are called operands. A sequence of operands and operators, like a + b - 5 , is called an expression. Python supports many operators for combining data objects into expressions.


1 Answers

The only meaningful comparison you can really use with None is if obj is None: (or if obj is not None:).

Comparison between different types has been removed from Python 3 for good reasons - they were a common source of errors and lead to confusion. For example

>>> "3" < 4 False 

In Python 3, you get a TypeError when comparing values of different types like str vs. int or anything vs. None.

>>> None < 0 Traceback (most recent call last):   File "<stdin>", line 1, in <module> TypeError: unorderable types: NoneType() < int() 

(I mean "comparing" in the sense of trying to determine which of two values is larger/smaller. Comparison for equality is OK - it will always return False if two object are of different types.)

I haven't found a reference in the docs for this, but in Learning Python, 4th edition, Mark Lutz writes on page 204:

[...] Comparisons of differently typed objects (e.g., a string and a list) work — the language defines a fixed ordering among different types, which is deterministic, if not aesthetically pleasing. That is, the ordering is based on the names of the types involved: all integers are less than all strings, for example, because "int" is less than "str".

like image 114
Tim Pietzcker Avatar answered Sep 20 '22 15:09

Tim Pietzcker