DEV Community

Taleb
Taleb

Posted on

Python comparison tips

1. Don’t compare boolean values to True or False using ==.

Yes:   if greeting:
No:    if greeting == True:

Worse: if greeting is True:

2. For sequences, (strings, lists, tuples), use the fact that empty sequences are false.

Yes: if not seq:
     if seq:
No:  if len(seq):
     if not len(seq):

3. Object type comparisons should always use isinstance() instead of comparing types directly.

Yes: if isinstance(obj, int):

No:  if type(obj) is type(1):

When checking if an object is a string, keep in mind that it might be a unicode string too! In Python 2, str and unicode have a common base class, basestring, so you can do:

if isinstance(obj, basestring):

Note that in Python 3, unicode and basestring no longer exist (there is only str) and a bytes object is no longer a kind of string (it is a sequence of integers instead).

4. Use string methods instead of the string module.

String methods are always much faster and share the same API with unicode strings. Override this rule if backwards compatibility with Pythons older than 2.0 is required.
Use ‘’.startswith() and ‘’.endswith() instead of string slicing to check for prefixes or suffixes.
startswith() and endswith() are cleaner and less error prone:

Yes: if foo.startswith(‘bar’): No: if foo[:3] == ‘bar’:
No:  if foo[:3] == 'bar':

Top comments (2)

Collapse
 
variac profile image
Variac

You should argument more why you should / shouldn't do something.
Without any reason told none can learn anything, also because nobody knows you and we don't know if your axioms are true or not.

Collapse
 
paddy3118 profile image
Paddy3118

It's good to give reasons which is missing from your first item. 😉