DEV Community

Taleb
Taleb

Posted on

2 1

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':

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

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. 😉

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay