1

For example:

match = re.search('...', str, re.IGNORECASE)
if match is not None:
    pass

# or
if match != None:
    pass

What is better?

avasin
  • 9,186
  • 18
  • 80
  • 127
  • 3
    Neither is better, since they differ in behaviour. –  Oct 27 '14 at 18:49
  • 1
    `is` is an identity operator, so it should be used ONLY when checking if the object has the _same_ memory address (singletons such as None qualify). Be careful as `'hello' == 'hello'`, but `'hello' is not 'hello'` – polvoazul Oct 27 '14 at 18:55
  • 1
    @polvoazul -- Actually, that depends on your python implementation. In Cpython, often `'hello' is 'hello'` _will_ be `True`, but that's not behavior that is guaranteed and so you shouldn't rely on it. :-) – mgilson Oct 27 '14 at 18:57
  • 1
    Alternatively you could avoid the question all together and do ```if not match``` which will evaluate ```True``` since ```bool(None)``` is ```False``` – wnnmaw Oct 27 '14 at 19:00
  • @wnnmaw but if match will have position 0? Btw, i should use `if match:` in my case, right? – avasin Oct 27 '14 at 19:01
  • I will answer my question: Yes, it just should be `if match`: https://docs.python.org/2/library/re.html#re.MatchObject – avasin Oct 27 '14 at 19:05
  • @avasin, right, point is you can avoid using ```==``` or ```is``` all together – wnnmaw Oct 27 '14 at 19:53
  • @mgilson -- Thats very correct, it will actually be true as I think Cpython keeps small strings as singletons, but as you said we should not rely on this! For curiosity, in cpython3.3: `print(20*'a' is 20*'a') => True` but `print(21*'a' is 21*'a') => False` – polvoazul Oct 29 '14 at 16:56

1 Answers1

5

From PEP 8:

Comparisons to singletons like None should always be done with is or is not, never the equality operators.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
  • @AaronHall You can create your own singletons http://stackoverflow.com/questions/42558/python-and-the-singleton-pattern http://stackoverflow.com/questions/31875/is-there-a-simple-elegant-way-to-define-singletons-in-python – David Heffernan Oct 27 '14 at 19:06
  • That might be better if added to your answer, lest it be interpreted differently. – Russia Must Remove Putin Oct 27 '14 at 19:42