Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid for-in looping over None in Python

Tags:

python

I know I can add some if blocks around to avoid this problem, but I am looking for a best practice or good/nice way to handle this kind of programming problem.

I am looping through the result of a function, without storing the result first in a separate variable; something like this:

for item in mycustimitemgetter.itter():
   dosomething()

The itter function is returning None instead of an empty list [], and Python throws an exception per None. This is correct python behavior and nothing's wrong with it. But I'm looking for a best practice solution to:

a) keep the code clean and simple (not storing the result in a var and do if != None, etc..)

b) treat a None return value like an empty list i.e. do not run the loop and silently ignore the fact that function returned a None value.

like image 521
tony994 Avatar asked May 09 '14 09:05

tony994


2 Answers

Perhaps, use the fact that both [] and None evaluate as False, but lists with contents don't:

for item in (mycustimitemgetter.itter() or []):
   dosomething()
like image 66
RemcoGerlich Avatar answered Oct 17 '22 05:10

RemcoGerlich


You have a method called itter() which returns an iterable object. I would say that given the name of the function, it's reasonable to say "the returned value should always be iterable". So, if you're returning a list, you should return an empty list if you have no values.

Code there to be executed. There is nothing wrong with adding:

if retval is None:
  return []
return retval

or

return retval or []

to the end of your itter() implementation, depending on the types in use.

Consider this: you wrote the code and you're facing this problem. What about someone else who's trying to use your code without knowing what you know. What do they expect?

Alternatively you should use Generators (if suitable). They contain a 'next' method (see the docs at the link), which you can return false if there are no values.

like image 9
Joe Avatar answered Oct 17 '22 04:10

Joe