def __get__(self, instance, owner): if instance is None: if hasattr(self.desc, '__get__'): return _lifted_desc_results(self.desc, self, instance, owner) else: return self else: if is_data_desc(self.desc): if hasattr(self.desc, '__get__'): return _lifted_desc_results(self.desc, self, instance, owner) if name_of(self, owner) in instance.__dict__: return instance.__dict__[name_of(self, owner)] elif hasattr(self.desc, '__get__'): return _lifted_desc_results(self.desc, self, instance, owner) else: return self
def __set__(self, instance, value): if is_data_desc(self.desc): if hasattr(self.desc, '__set__'): # delegate if __set__ exists self.desc.__set__(instance, value) else: # bad call if it's a data descriptor without __set__ raise AttributeError('__set__') else: # delegate to instance dictionary name = name_of(self, type(instance)) instance.__dict__[name] = value
def __delete__(self, instance): if hasattr(self.desc, '__delete__'): self.desc.__delete__(instance) elif is_data_desc(self.desc): raise AttributeError('__delete__') else: try: del instance.__dict__[name_of(self, type(instance))] except KeyError as e: raise AttributeError(e)
def _name(self, instance): if instance is None: return "<unknown name>" name = name_of(self, type(instance)) self._name = lambda inst: name return name
def test_find_name_on_sub_class(self): result = name_of(SubClass.attr, SubClass) self.assertEqual(result, SubClass.attrname)
def test_find_name_on_class(self): result = name_of(Class.attr, Class) self.assertEqual(result, Class.attrname)
def __str__(self): attrname = name_of(self.descriptor, self.owner) return "Unbound Attribute '{cls}.{attr}'".format( cls=self.owner.__name__, attr=attrname)
def _name(self, instance): name = self.mangle(name_of(self, type(instance))) self._name = lambda inst: name del self.mangle return name
def _set_name(self, owner): if self._name is None: self._name = name_of(self, owner) self._secret_name = '_' + self._name
def _name_for(self, owner): try: return self._names[owner] except KeyError: self._names[owner] = name_of(self, owner) return self._names[owner]