Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

web2py

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?

like image 643
dmmd Avatar asked Aug 05 '12 13:08

dmmd


3 Answers

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)
like image 151
Martijn Pieters Avatar answered Sep 30 '22 10:09

Martijn Pieters


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']:

like image 22
Inbar Rose Avatar answered Sep 30 '22 10:09

Inbar Rose


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)

like image 35
Medardo Rodriguez Avatar answered Sep 30 '22 09:09

Medardo Rodriguez