On 20/06/2023 06.12, Neal Becker via Python-list wrote:
On Mon, Jun 19, 2023 at 12:42 PM Chris Angelico via Python-list <
python-list@python.org> wrote:

On Tue, 20 Jun 2023 at 02:37, Peter Bona via Python-list
<python-list@python.org> wrote:

Hi

I am wondering if there has been any discussion why NoneType  is not
iterable My feeling is that it should be.
Sometimes I am using API calls which return None.
If there is a return value (which is iterable) I am using a for loop to
iterate.

Now I am getting 'TypeError: 'NoneType' object is not iterable'.

(Examples are taken from here
https://rollbar.com/blog/python-typeerror-nonetype-object-is-not-iterable/
)
Example 1:
mylist = None
for x in mylist:
     print(x)  <== will raise TypeError: 'NoneType' object is not iterable
Solution: extra If statement
if mylist is not None:
     for x in mylist:
         print(x)


I think Python should handle this case gracefully: if a code would
iterate over None: it should not run any step. but proceed the next
statement.

Has this been discussed or proposed?


Try this instead:

for x in mylist or ():

Now a None list will skip iteration entirely, allowing you to get the
effect you want :)

ChrisA
--
https://mail.python.org/mailman/listinfo/python-list

I prefer iteration of None to be an error, as in my usage it usually
indicates a mistake that I'd want to catch

Agreed!

A better approach is that the API return (perhaps a tuple of) both "status" and "return_value", rather than overloading the latter.

That said, apparently the OP use-case is for when there is no interest in status/catch, eg where a 'nothing' answer is THE answer.

--
Regards,
=dn
--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to