How to check if list variable exists in python mako template?-Collection of common programming errors

Assuming I have the following in my template:

% if not mydict['somekey'] is UNDEFINED:
    ${mydict['somekey'][0]['hellothere']}
% endif    

My issue is the above does not work as mydict['somekey'] is always an array, but it could be empty. I want to be able to check to make sure that if mydict['somekey'] is defined, I can add a check to make sure either 1) the list size is greater than 0 (from inside the template) or if the mydict['somekey'] has elements in it so that I can print out what is in mydict['somekey'][0]['hellothere'] when available.

What must I do? I keep getting an:

IndexError: list index out of range

with the above

  1. PEP 8 recommends:

    For sequences, (strings, lists, tuples), use the fact that empty sequences are false.

    So really you don’t need to check the length and just check it like this:

    % if mydict.get('somekey'):
        ${mydict['somekey'][0]['hellothere']}
    % endif
    

Originally posted 2013-11-09 23:37:51.