"object of type 'NoneType' has no len()" error
Asked Answered
C

4

22

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?

Cinnabar answered 5/8, 2012 at 13:30 Comment(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".Arlyn
C
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)
Carouse answered 5/8, 2012 at 13:33 Comment(0)
P
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']:

Petticoat answered 5/8, 2012 at 13:35 Comment(5)
Actually it was due the assignment of some "None" to images['cover'] (as pointed by Martjin). But thanks!Cinnabar
in your post you said that this line if len(images['cover']) == 0: gave you the error...Petticoat
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 :)Petticoat
Yes. In the second iteration inside the for, images['cover'] type was "None", as the first iteration assigned some "None" value to it.Cinnabar
Oh, yeah, that's true. Will do that! Thanks :)Cinnabar
N
6

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.

Necktie answered 4/10, 2022 at 19:27 Comment(0)
E
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)

Ephod answered 5/8, 2012 at 22:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.