-1
def send_ivr_calls(sp_orders, base_url, api_key, extra_data):
    for contact in sp_orders:
        if len(contact) == 10:
            contact = '0'+contact

File "views.py", line 43, in calls if len(contact) == 10:
TypeError: object of type 'NoneType' has no len()

How can I check whether the sp_orders list does not contain any Nones?

tzot
  • 92,761
  • 29
  • 141
  • 204
Taniya
  • 248
  • 2
  • 8

2 Answers2

3

Try this:

def send_ivr_calls(sp_orders, base_url, api_key, extra_data):
    for contact in sp_orders:
        if contact and len(contact) == 10:
                contact = '0'+contact

This is ensures contact is not None before you try to get its length. Credit to @Moses Koledoye for pointing out short-circuiting.

Kyle Higginson
  • 922
  • 6
  • 11
  • 2
    Why not use one *if* clause and shortcircuit with `and`. Although the parser is very likely to fix it so it might not be much of a problem. – Moses Koledoye Sep 21 '17 at 10:20
  • 3
    `if contact and len(contact) == 10` won't break. If contact is *falsy*, it's length will never be checked. – Moses Koledoye Sep 21 '17 at 10:26
  • @Kyle Higginson, [good thread about short-circuiting](https://stackoverflow.com/questions/2580136/does-python-support-short-circuiting) – CommonSense Sep 21 '17 at 10:30
1
if contact is not None and len(contact) == 10:
    contact = '0'+contact
Dmitry
  • 6,716
  • 14
  • 37
  • 39