How not to write Python code
pythonbest-practicescode-qualityanti-patterns
Abstraction: Python anti-patterns and idiomatic best practices to avoid common mistakes
Key points:
- Use the standard library ("batteries included") before adding dependencies; e.g. use BaseHTTPServer instead of Twisted for simple HTTP
- Avoid
from foo import *(pollutes namespace); prefer explicit imports orimport foo - Use Pythonic patterns — e.g. dicts + function objects to emulate switch/case, since Python has none
- Write docstrings and tests (unittest or doctest) during development, not after; use exception subclasses not bare returns for errors
- Use built-ins like
isinstance(arg, (TypeA, TypeB)),getattr/setattr, and avoidarg.__class__ == MyClass - Use code metrics tools (e.g. PyLint) and interactive shells (iPython) during development; avoid messing with sys.path
Connections: Pylint · Ipython · Python · Software Engineering · Code Quality