Fundamentals 5 min read

Common Bad Practices in Python and How to Avoid Them

This article highlights several typical Python pitfalls—including mutable default arguments, improper file handling, catching overly broad exceptions, misunderstanding the for‑else construct, and inefficient dictionary iteration—and provides clearer, more reliable alternatives for each case.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
Common Bad Practices in Python and How to Avoid Them

Many articles teach how to write good Python code, but this piece focuses on the opposite: common bad habits that can hide bugs or make code harder to maintain. The examples are written for Python 3.6.

1. Using mutable objects as default function arguments – The article shows a function that unintentionally shares a list across calls, leading to unexpected results. Replacing the mutable default with None and initializing inside the function resolves the issue.

2. File handling – Beginners often open files without using a context manager, forgetting to close them. The article recommends the with open(...) pattern, which automatically handles resource cleanup and results in cleaner code.

3. Catching all exceptions – Using a bare except Exception can swallow unrelated errors such as KeyboardInterrupt or AssertionError . Instead, catch specific exceptions like ValueError , AttributeError , or TypeError and handle them appropriately.

4. Ignoring Python's for…else syntax – The article explains that the else block runs only when the loop finishes without a break . It demonstrates a more idiomatic way to check for the presence of an odd number in a list using this construct.

5. Iterating over dictionary keys – Instead of looping over dict.items() and then accessing the key, the article shows that iterating directly over the dictionary yields the keys, making the code clearer and more concise.

These points reflect personal preferences rather than strict rules; the goal is to choose the most suitable practice for each situation.

debuggingPythonProgrammingBest Practicescode qualityexceptionsmutable defaults
Python Programming Learning Circle
Written by

Python Programming Learning Circle

A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.