I believe every Python coder has met this error at least once when running a code like this:

def func(args=None):
  for arg in args:
    pass

func()
Traceback (most recent call last):
  File "<stdin>", line 5, in <module>
  File "<stdin>", line 2, in func
TypeError: 'NoneType' object is not iterable

Whether you are new to Python or not, you’d immediately know what problem is. None is not iterable, which makes a lot of sense. This type of error often comes with the default function argument value or returned value of a function.

I was reviewing a commit and got reminded of this error. A normal quick fix is to add if clause to check args, e.g.:

if args:
  for arg in args:
    pass

However, as per line length guideline in PEP8, you’d really hate to add another level of indentation. But, I did that quick fix anyway when I saw the error and continued to review, that’s what I always did, my go-to fix.

A better practice is to validate every arguments before doing any process, e.g.

args = args or []
for arg in args:
  pass

This is a simplified case and generally I would just use or to do the trick. A more readable (and robust) way is to check args is None, for this case, or is enough, but may not be in other uses when the argument is little complicated to initialize or to validate.

But this was not what came to my mind when I got the code running with my go-to fix, what I thought was:

for arg in args or ():
  pass

Honestly, this is not a good Python code in my opinion, because it’s little hard to read since () is mingled within for and there might have chances that args might be iterated more than once. Nevertheless, as a quick fix in order to get pass the code, it’s fine.