Hacker News new | ask | show | jobs
by coconutrandom 3325 days ago
So Django Templates also use dot notation lookups for dict, lists, and objects[0]

  Dictionary lookup, attribute lookup and list-index lookups are implemented with a dot notation:

  {{ my_dict.key }}
  {{ my_object.attribute }}
  {{ my_list.0 }}
  If a variable resolves to a callable, the 
  template system will call it with no 
  arguments and use its result instead of the callable.
Which leads to some interesting and confusing errors if you start iterating over `.items` and you get a callable and not the list you expect.

  In [17]: a = {"a": 1, "items": {"b": {"c": {}}}}
    ...: a_box = Box(a)
    ...: a_box
    ...: 
  Out[17]: <Box: {'a': 1, 'items': {'b': {'c': {}}}}>

  In [18]: a_box
  Out[18]: <Box: {'a': 1, 'items': {'b': {'c': {}}}}>

  In [19]: a_box.items
  Out[19]: <function items>

  In [20]: a_box.a
  Out[20]: 1

[0] https://docs.djangoproject.com/en/1.11/topics/templates/#var...

EDIT: This came up because our JSON commonly uses `items` as a key for a list of items, which I expect to be at `a_dict['items']`, and it has nothing to do with python's `a_dict.items`.