dictionary.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. #!/usr/bin/env python
  2. """A wrapper for dictionaries."""
  3. from . import apifunction
  4. from . import computedobject
  5. # Using lowercase function naming to match the JavaScript names.
  6. # pylint: disable=g-bad-name
  7. class Dictionary(computedobject.ComputedObject):
  8. """An object to represent dictionaries."""
  9. _initialized = False
  10. # Tell pytype to not complain about dynamic attributes.
  11. _HAS_DYNAMIC_ATTRIBUTES = True
  12. def __init__(self, arg=None):
  13. """Construct a dictionary.
  14. Args:
  15. arg: This constructor accepts the following args:
  16. 1) Another dictionary.
  17. 2) A list of key/value pairs.
  18. 3) A null or no argument (producing an empty dictionary)
  19. """
  20. self.initialize()
  21. if isinstance(arg, dict):
  22. super(Dictionary, self).__init__(None, None)
  23. self._dictionary = arg
  24. else:
  25. self._dictionary = None
  26. if (isinstance(arg, computedobject.ComputedObject)
  27. and arg.func
  28. and arg.func.getSignature()['returns'] == 'Dictionary'):
  29. # If it's a call that's already returning a Dictionary, just cast.
  30. super(Dictionary, self).__init__(arg.func, arg.args, arg.varName)
  31. else:
  32. # Delegate everything else to the server-side constructor.
  33. super(Dictionary, self).__init__(
  34. apifunction.ApiFunction('Dictionary'), {'input': arg})
  35. @classmethod
  36. def initialize(cls):
  37. """Imports API functions to this class."""
  38. if not cls._initialized:
  39. apifunction.ApiFunction.importApi(cls, 'Dictionary', 'Dictionary')
  40. cls._initialized = True
  41. @classmethod
  42. def reset(cls):
  43. """Removes imported API functions from this class."""
  44. apifunction.ApiFunction.clearApi(cls)
  45. cls._initialized = False
  46. @staticmethod
  47. def name():
  48. return 'Dictionary'
  49. def encode(self, opt_encoder=None):
  50. if self._dictionary is not None:
  51. return opt_encoder(self._dictionary)
  52. else:
  53. return super(Dictionary, self).encode(opt_encoder)
  54. def encode_cloud_value(self, opt_encoder=None):
  55. if self._dictionary is not None:
  56. return {'valueReference': opt_encoder(self._dictionary)}
  57. else:
  58. return super(Dictionary, self).encode_cloud_value(opt_encoder)