ee_string.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. #!/usr/bin/env python
  2. """A wrapper for strings."""
  3. # pylint: disable=g-bad-import-order
  4. from . import apifunction
  5. from . import computedobject
  6. from . import ee_exception
  7. # Using lowercase function naming to match the JavaScript names.
  8. # pylint: disable=g-bad-name
  9. class String(computedobject.ComputedObject):
  10. """An object to represent strings."""
  11. _initialized = False
  12. # Tell pytype to not complain about dynamic attributes.
  13. _HAS_DYNAMIC_ATTRIBUTES = True
  14. def __init__(self, string):
  15. """Construct a string wrapper.
  16. This constructor accepts the following args:
  17. 1) A bare string.
  18. 2) A ComputedObject returning a string.
  19. Args:
  20. string: The string to wrap.
  21. """
  22. self.initialize()
  23. if isinstance(string, str):
  24. super(String, self).__init__(None, None)
  25. elif isinstance(string, computedobject.ComputedObject):
  26. if string.func and string.func.getSignature()['returns'] == 'String':
  27. # If it's a call that's already returning a String, just cast.
  28. super(String, self).__init__(string.func, string.args, string.varName)
  29. else:
  30. super(String, self).__init__(apifunction.ApiFunction('String'), {
  31. 'input': string
  32. })
  33. else:
  34. raise ee_exception.EEException(
  35. 'Invalid argument specified for ee.String(): %s' % string)
  36. self._string = string
  37. @classmethod
  38. def initialize(cls):
  39. """Imports API functions to this class."""
  40. if not cls._initialized:
  41. apifunction.ApiFunction.importApi(cls, 'String', 'String')
  42. cls._initialized = True
  43. @classmethod
  44. def reset(cls):
  45. """Removes imported API functions from this class."""
  46. apifunction.ApiFunction.clearApi(cls)
  47. cls._initialized = False
  48. @staticmethod
  49. def name():
  50. return 'String'
  51. def encode(self, opt_encoder=None):
  52. if isinstance(self._string, str):
  53. return self._string
  54. else:
  55. return self._string.encode(opt_encoder)
  56. def encode_cloud_value(self, opt_encoder=None):
  57. if isinstance(self._string, str):
  58. return {'constantValue': self._string}
  59. else:
  60. return self._string.encode_cloud_value(opt_encoder)