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