Suggesting for overloading the assign operator

Ian Bicking ianb at colorstudy.com
Tue Jul 1 18:13:01 EDT 2003


On Tue, 2003-07-01 at 13:01, Alan Kennedy wrote:
> Rim wrote:
> 
> > What do you think about providing a statement to assign values
> > without assigning type?
> > 
> > '=' statement assigns value and type
> > ':=' statement assigns value ony
> 
> I think the concept has some merit. I think that sometimes it useful to ensure
> that the target of a rebind operation have the same type as the object which was
> bound before the rebind.
> 
> I know that the same effect can be achieved by descriptors or overriding
> "setattr" et al. Or something like this

Or maybe:

class stricttype(object):

    counter = 1

    def __init__(self, required_type, doc=None, real_attr=None):
        self.required_type = required_type
        if not real_attr:
            real_attr = '_stricttype_attr_%i' % stricttype.counter
            stricttype.counter += 1
        self.real_attr = real_attr
        self.doc = doc

    def __set__(self, obj, value):
        if not isinstance(value, self.required_type):
            raise TypeError, 'must be of type %r' % self.required_type
        setattr(obj, self.real_attr, value)

    def __get__(self, obj, cls):
        return getattr(obj, self.real_attr)

    def __del__(self, obj):
        delattr(obj, self.real_attr)

    def __doc__(self, obj):
        return self.doc


class IntPoint(object):

    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __str__(self):
        return 'Point: (%i, %i)' % (self.x, self.y)

    x = stricttype(int)
    y = stricttype(int)

>>> p = IntPoint(1, 1)
>>> p
Point: (1, 1)
>>> p.x = 2
>>> p
Point: (2, 1)
>>> p.x = 2.2
Traceback (most recent call last):
  File "stricttype.py", line 44, in ?
    p.x = 2.2
  File "stricttype.py", line 15, in __set__
    raise TypeError, 'must be of type %r' % self.required_type
TypeError: must be of type <type 'int'>


If we're talking about optimizations, there's no reason something like
Psyco couldn't specifically look for specific descriptors like
stricttype, and probably replace that implementation with something
better optimized.

  Ian







More information about the Python-list mailing list