Python Mutable Defaults Are The Source of All Evil

Florimond Manca on August 14, 2018

Today, I wanted to share a quick life-saving advice about a common mistake Python developers still tend to make. TL;DR Do not use mutab... [Read Full]
markdown guide
 

Would you consider

seq = seq or []

a viable alternative to your if-construction?

 

Yes, I would see that as a viable alternative :-) — although I would argue that:

  • I see the if X is None check in Python code more often — not sure it means anything in terms of "pythonicism", though!
  • This only works when the default is simple enough to build. If it needs multiple lines to be built, we'll have to resort to if X is None anyway.
 

Another option is using a non mutable type like a tuple

 

Yep, that would solve it if your argument can be transformed to use a non-mutable version.
However, Python is already so confusing on types that I wouldn’t recommend providing a tuple if you’re to use a list afterwards.
I like to use type annotations, so annotating an argument as a List while providing an empty tool for the default would look suspicious. ;)

code of conduct - report abuse