proto-PEPs: __bind__ and __return__?

Delaney, Timothy tdelaney at avaya.com
Mon May 13 03:07:53 EDT 2002


> From: James T. Dennis [mailto:jadestar at idiom.com]

I'm going to ignore the proposal itself right now, but I do want to look at
a few points which I think would make this proposal more pythonic.

>  What if we created two special methods: __bind__ and __return__
>  which are (if present) invoked by the assignment operator.  If

You never specify what __return__ is meant to do ...

>  >>> class Constant(object):
>  ...	def __bind__(self,target):
>  ...		if unbound('self'): 
>  ...			self=target
>  ...		else: 
>  ...			raise ConstantError, 'Cannot rebind to constant'
>  >>> a = Constant(5)
>  >>> a = 6
>  Traceback (most recent call last):
>    File "<stdin>", line 1, in ?
>  ConstantError: Cannot rebind to constant

The __bind__ method would need to return the object that should be bound to
the name.

class Constant (object):
    def __bind__ (self, target):
        return self # will always rebind to itself

class Constant (object):
    def __bind__ (self, target):
        raise ConstantError, 'Cannot rebind to constant'

Otherwise you are just attempting to rebind the name 'self', which would
invoke infinite recursion. Plus, returning what you want to bind would be
the more pythonic way to do it.

unbound() could only work with anonymous instances ... in which case,
__bind__ would not be called (because __bind__ would only be called when
rebinding, which means the object must have previously been bound). The only
case where this would not be the case would be in sequence (tuple) unpacking
... and that is already defined (binding to the names declared in the
anonymous sequence). So unbound() is both useless and unfeasible.

I think __rebind__ would be a better name - unambiguous.

>  >>> class ConstrainType(object):
>  ... 	def __bind__(self,target):
>  ...		if unbound('self') or isinstance(target,self.__class__):
>  ...			self=target
>  ...		else:
>  ...			raise ValueError, 'Type Constraint Violated'

class ConstrainType(object):
    def __bind__(self,target):
        if isinstance(target,self.__class__):
            return target
        else:
            raise ValueError, 'Type Constraint Violated'

Tim Delaney





More information about the Python-list mailing list