21

I'm seeing weird behavior on this code:

images = dict(cover=[],second_row=[],additional_rows=[])

for pic in pictures:
    if len(images['cover']) == 0:
        images['cover'] = pic.path_thumb_l
    elif len(images['second_row']) < 3:
        images['second_row'].append(pic.path_thumb_m)
    else:
        images['additional_rows'].append(pic.path_thumb_s)

My web2py app gives me this error:

if len(images['cover']) == 0:
TypeError: object of type 'NoneType' has no len()

I can't figure out what's wrong in this. Maybe some scope issue?

Nathaniel Ford
  • 20,545
  • 20
  • 91
  • 102
dmmd
  • 2,938
  • 4
  • 33
  • 41
  • 1
    You are asking for the Length of a variable that contains None. None is a special value (of type NoneType) that has no length. Before you check for the length of something, first check to make sure it does not have the value "None". – Eric Leschinski May 18 '15 at 14:12

4 Answers4

17

You assign something new to images['cover']:

images['cover'] = pic.path_thumb_l

where pic.path_thumb_l is None at some point in your code.

You probably meant to append instead:

images['cover'].append(pic.path_thumb_l)
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
16

your problem is that

if len(images['cover']) == 0:

checks the LENGTH of the value of images['cover'] what you meant to do is check if it HAS a value.

do this instead:

if not images['cover']:

Inbar Rose
  • 41,843
  • 24
  • 85
  • 131
  • Actually it was due the assignment of some "None" to images['cover'] (as pointed by Martjin). But thanks! – dmmd Aug 05 '12 at 13:37
  • in your post you said that this line `if len(images['cover']) == 0:` gave you the error... – Inbar Rose Aug 05 '12 at 13:38
  • 2
    either way, you should change your code to `if not images['cover']:` instead, since if the length is not 0 it will already have a value, this way its more pythonic :) – Inbar Rose Aug 05 '12 at 13:39
  • Yes. In the second iteration inside the for, `images['cover']` type was "None", as the first iteration assigned some "None" value to it. – dmmd Aug 05 '12 at 13:39
  • Oh, yeah, that's true. Will do that! Thanks :) – dmmd Aug 05 '12 at 13:40
3

We can also see the type in the same condition, to avoid something if you want, like

if myArray is None:
    #Do something when array has no len()
else:
    #Do something when array has elements and has len()

In my case I was looking for something in the array, but only if has something, when id does not, was None the type and I need to create it. Hope this works for someones.

Alfa Rojo
  • 165
  • 8
2

The first time you assign: images['cover'] = pic.path_thumb_l, it replaces the value of the empty list initially stored in images['cover'] with the value of pic.path_thumb_l which is None.

Maybe your code in this line must be images['cover'].append(pic.path_thumb_l)

Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335