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