Behavioural identity - a short discussion

Kay Schluehr kay.schluehr at gmx.net
Mon Apr 11 12:13:50 EDT 2005


Terry Reedy wrote:
> "Kay Schluehr" <kay.schluehr at gmx.net> wrote in message
> news:1113165441.978711.64860 at z14g2000cwz.googlegroups.com...
> > class A(object):
> >    def __init__(self):
> >        raise NotImplemented
> >
> > We can regard class A as a "pure abstract" class. It is impossible
to
> > create instances of A.
>
> You see that parameter 'self'?  When __init__ is called, it is bound
to an
> already created instance of A.

Yes. I've forgotten.

This would make sense and instantiable subclasses have to override
__new__.

class A(object):
    def __new__(cls):
        raise NotImplemented

    def __init__(self):
        self.x = 0

> How soon the last reference goes away I am
> not sure.  If you change the raise statement to 'raise
> SomeException(self)', then that instance will become bound to the
'args'
> attribute of the resulting exception object.  That exception object
can in
> turn be get captured by an 'except SomeException, obj' statement.
The
> binding of 'obj' persists after the except statement.

I considered the statement "raise Implemented" as kind of pattern: an
implementation that is at the same time a "declaration" for some client
who understands behavioural equivalence. One can not go much further
with the idea of scripting :)

On the other hand for real applications it may be wiser to use
decorators, because they are a standard and easy to use and to
understand.

This one would be completely appropriate:

def not_implemented(f):
    setattr(f,"not_implemented",True)
    return f

class A(object):
   @not_implemented
   def f(self):
       pass


Allthough this one

class A(object):
   def f(self):
       raise NotImplemented

would be minimalistic and somehow innocent.

> To abort object creation, write a metaclass with __new__ and raise an

> exception there.

Yes.

>
> > Thinking in Python makes live easier because we can not only
> > check interfaces superficially but we can inspect the code and we
can
> > compare two code-objects on the behavioural level with a certain
> > accuracy.
>
> You are actually thinking in terms of the CPython implementation, not

> Python itself, which is fine as long as you don't expect
CPython-specific
> introspection to work with other implementations.  But it is pretty
neat
> sometimes.
>
> Terry J. Reedy

I think it is scripting putting to the extreme. I don't know much about
the introspective capabilities of Jython and IronPython because I don't
use them but without them not even a variant of Pychecker will work for
either of the two Pychecker versions ( i.e. AST / bytecode ).

Ciao,
Kay




More information about the Python-list mailing list