[Python-3000] PEP 3133: Introducing Roles

Collin Winter collinw at gmail.com
Mon May 14 22:03:44 CEST 2007


On 5/13/07, Steven Bethard <steven.bethard at gmail.com> wrote:
> On 5/13/07, Collin Winter <collinw at gmail.com> wrote:
> > PEP: 3133
> > Title: Introducing Roles
> [snip]
> > * Roles provide a way of indicating a object's semantics and abstract
> >   capabilities.  A role may define abstract methods, but only as a
> >   way of delineating an interface through which a particular set of
> >   semantics are accessed.
> [snip]
> > * Abstract base classes, by contrast, are a way of reusing common,
> >   discrete units of implementation.
> [snip]
> >   Using this abstract base class - more properly, a concrete
> >   mixin - allows a programmer to define a limited set of operators
> >   and let the mixin in effect "derive" the others.
>
> So what's the difference between a role and an abstract base class
> that used @abstractmethod on all of its methods? Isn't such an ABC
> just "delineating an interface"?
>
> > since the ``OrderingMixin`` class above satisfies the interface
> > and semantics expressed in the ``Ordering`` role, we say the mixin
> > performs the role: ::
> >
> >   @perform_role(Ordering)
> >   class OrderingMixin:
> >     def __ge__(self, other):
> >       return self > other or self == other
> >
> >     def __le__(self, other):
> >       return self < other or self == other
> >
> >     def __ne__(self, other):
> >       return not self == other
> >
> >     # ...and so on
> >
> > Now, any class that uses the mixin will automatically -- that is,
> > without further programmer effort -- be tagged as performing the
> > ``Ordering`` role.
>
> But why is::
>
>     performs(obj, Ordering)
>
> any better than::
>
>     isinstance(obj, Ordering)
>
> if Ordering is just an appropriately registered ABC?

There really is no difference between roles and all- at abstractmethod
ABCs. From my point of view, though, roles win because they don't
require any changes to the interpreter; they're a much simpler way of
expressing the same concept. You may like adding the extra complexity
and indirection to the VM necessary to support
issubclass()/isinstance() overriding, but I don't.

Collin Winter


More information about the Python-3000 mailing list