notebooknode.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. """NotebookNode - adding attribute access to dicts"""
  2. from ipython_genutils.ipstruct import Struct
  3. from collections import Mapping
  4. class NotebookNode(Struct):
  5. """A dict-like node with attribute-access"""
  6. def __setitem__(self, key, value):
  7. if isinstance(value, Mapping) and not isinstance(value, NotebookNode):
  8. value = from_dict(value)
  9. super(NotebookNode, self).__setitem__(key, value)
  10. def update(self, *args, **kwargs):
  11. """
  12. A dict-like update method based on CPython's MutableMapping `update`
  13. method.
  14. """
  15. if len(args) > 1:
  16. raise TypeError('update expected at most 1 arguments, got %d' %
  17. len(args))
  18. if args:
  19. other = args[0]
  20. if isinstance(other, Mapping):
  21. for key in other:
  22. self[key] = other[key]
  23. elif hasattr(other, "keys"):
  24. for key in other.keys():
  25. self[key] = other[key]
  26. else:
  27. for key, value in other:
  28. self[key] = value
  29. for key, value in kwargs.items():
  30. self[key] = value
  31. def from_dict(d):
  32. """Convert dict to dict-like NotebookNode
  33. Recursively converts any dict in the container to a NotebookNode.
  34. This does not check that the contents of the dictionary make a valid
  35. notebook or part of a notebook.
  36. """
  37. if isinstance(d, dict):
  38. return NotebookNode({k: from_dict(v) for k, v in d.items()})
  39. elif isinstance(d, (tuple, list)):
  40. return [from_dict(i) for i in d]
  41. else:
  42. return d