attrsettr.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. # coding: utf-8
  2. """Mixin for mapping set/getattr to self.set/get"""
  3. # Copyright (C) PyZMQ Developers
  4. # Distributed under the terms of the Modified BSD License.
  5. import errno
  6. from . import constants
  7. class AttributeSetter(object):
  8. def __setattr__(self, key, value):
  9. """set zmq options by attribute"""
  10. if key in self.__dict__:
  11. object.__setattr__(self, key, value)
  12. return
  13. # regular setattr only allowed for class-defined attributes
  14. for obj in self.__class__.mro():
  15. if key in obj.__dict__:
  16. object.__setattr__(self, key, value)
  17. return
  18. upper_key = key.upper()
  19. try:
  20. opt = getattr(constants, upper_key)
  21. except AttributeError:
  22. raise AttributeError("%s has no such option: %s" % (
  23. self.__class__.__name__, upper_key)
  24. )
  25. else:
  26. self._set_attr_opt(upper_key, opt, value)
  27. def _set_attr_opt(self, name, opt, value):
  28. """override if setattr should do something other than call self.set"""
  29. self.set(opt, value)
  30. def __getattr__(self, key):
  31. """get zmq options by attribute"""
  32. upper_key = key.upper()
  33. try:
  34. opt = getattr(constants, upper_key)
  35. except AttributeError:
  36. raise AttributeError("%s has no such option: %s" % (
  37. self.__class__.__name__, upper_key)
  38. )
  39. else:
  40. from zmq import ZMQError
  41. try:
  42. return self._get_attr_opt(upper_key, opt)
  43. except ZMQError as e:
  44. # EINVAL will be raised on access for write-only attributes.
  45. # Turn that into an AttributeError
  46. # necessary for mocking
  47. if e.errno == errno.EINVAL:
  48. raise AttributeError("{} attribute is write-only".format(key))
  49. else:
  50. raise
  51. def _get_attr_opt(self, name, opt):
  52. """override if getattr should do something other than call self.get"""
  53. return self.get(opt)
  54. __all__ = ['AttributeSetter']