[Tutor] Descriptors and type declaration order

Steven D'Aprano steve at pearwood.info
Thu Jul 14 15:01:19 CEST 2011


Knacktus wrote:
> Hi guys,
> 
> I've got the following (not working) code:
[...]
> The problem is that the descriptors are created when the module is
> evaluated. But at this time the class BaseItem is not known yet. Any ideas?

Yes -- don't do that.

What are you actually trying to accomplish? Embedding an instance of the 
class in the class is a means to an end, not the end itself. What 
problem are you trying to solve? There may be a better way.

My *guess* is that you're trying to create properties that automatically 
check their type. As much as I think that's probably a bad idea, this is 
how I would solve that:


import functools

class CheckedProperty(property):
     def __init__(self, type, fget=None, fset=None, fdel=None, doc=None):
         if fset is not None:
             fset = self.checked(type, fset)
         super().__init__(fget, fset, fdel, doc)
     def checked(self, type, func):
         @functools.wraps(func)
         def inner(self, value):
             if not isinstance(value, type):
                 raise TypeError('invalid type')
             return func(self, value)
         return inner

class Test(object):
     def _getx(self):
         return self.__x
     def _setx(self, value):
         self.__x = value
     x = CheckedProperty(str, _getx, _setx)



But please don't over-use isinstance checks. They're a bad idea.


-- 
Steven



More information about the Tutor mailing list