Search code examples
pythonmako

How to check if list variable exists in python mako template?


Assuming I have the following in my template:

% if not mydict['somekey'] is UNDEFINED:
    ${mydict['somekey'][0]['hellothere']}</td></tr>
% 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


Solution

  • 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']}</td></tr>
    % endif