Search code examples
pythonmako

How to check variable type in mako?


I have a nested dict of dicts in a mako template and am trying to loop through them to print out their keys.

%for fruit in mydict['fruits']:
   ${fruit}
   % for nutrition in mydict['fruits'][fruit]:
      ${nutrition}
   % endfor
%endfor

The issue I am having is with the line: " % for nutrition in mydict['fruits'][fruit]:"

TypeError: 'int' object is not iterable.

How can I check if mydict['fruits'][fruit] is a list or an int?


Solution

  • Typically, mydict['fruits'] is a dictionary, and your fruit will be the keys. Indexing mydict['fruits'] with fruit like mydict['fruits'][fruit] will result in getting the single item, which apparently, is an integer, and not a list of nutritions. Why it is an integer, is caused somewhere else in your code.

    >>> for fruit in mydict['fruits']:
    ...   print fruit, mydict['fruits'][fruit]
    ...   for nutrition in mydict['fruits'][fruit]:
    ...     print nutrition
    ... 
    kiwi 2
    Traceback (most recent call last):
      File "<stdin>", line 3, in <module>
    TypeError: 'int' object is not iterable
    

    Update

    (Confusingly, the question changed, and thus my answer needs updating.)

    You could use isinstance(mydict['fruits'][fruit], list) and variants.

    Or perhaps better, make sure things are always a list; i.e., put the type-checking logic in the Python code proper, and not in the template code. Because practically, why would an integer by a nutrient?

    Also, consider simpler ways of iterating through a dict (assuming this works in mako):

    >>> for fruit, nutritions in mydict['fruits'].items():
    ...     if isinstance(nutritions, list):
    ...        for nutrition in nutritions:
    ...            print nutrition