Following system colour scheme Selected dark colour scheme Selected light colour scheme

Python Enhancement Proposals

PEP 3119 – Introducing Abstract Base Classes

Author:
Guido van Rossum <guido at Python.org>, Talin <viridia at gmail >
Status:
Final
Type:
Standards Track
Created:
18-Apr-2007
Python-Version:
3.0
Post-History:
26-Apr-2007, 11-May-2007

Table of Contents

Abstract

This is a proposal to add Abstract Base Class (ABC) support to Python 3000. It proposes:

  • A way to overloadisinstance()andissubclass().
  • A new moduleabcwhich serves as an “ABC support framework”. It defines a metaclass for use with ABCs and a decorator that can be used to define abstract methods.
  • Specific ABCs for containers and iterators, to be added to the collections module.

Much of the thinking that went into the proposal is not about the specific mechanism of ABCs, as contrasted with Interfaces or Generic Functions (GFs), but about clarifying philosophical issues like “what makes a set”, “what makes a mapping” and “what makes a sequence”.

There’s also a companionPEP 3141,which defines ABCs for numeric types.

Acknowledgements

Talin wrote the Rationale below[1]as well as most of the section on ABCs vs. Interfaces. For that alone he deserves co-authorship. The rest of the PEP uses “I” referring to the first author.

Rationale

In the domain of object-oriented programming, the usage patterns for interacting with an object can be divided into two basic categories, which are ‘invocation’ and ‘inspection’.

Invocation means interacting with an object by invoking its methods. Usually this is combined with polymorphism, so that invoking a given method may run different code depending on the type of an object.

Inspection means the ability for external code (outside of the object’s methods) to examine the type or properties of that object, and make decisions on how to treat that object based on that information.

Both usage patterns serve the same general end, which is to be able to support the processing of diverse and potentially novel objects in a uniform way, but at the same time allowing processing decisions to be customized for each different type of object.

In classical OOP theory, invocation is the preferred usage pattern, and inspection is actively discouraged, being considered a relic of an earlier, procedural programming style. However, in practice this view is simply too dogmatic and inflexible, and leads to a kind of design rigidity that is very much at odds with the dynamic nature of a language like Python.

In particular, there is often a need to process objects in a way that wasn’t anticipated by the creator of the object class. It is not always the best solution to build in to every object methods that satisfy the needs of every possible user of that object. Moreover, there are many powerful dispatch philosophies that are in direct contrast to the classic OOP requirement of behavior being strictly encapsulated within an object, examples being rule or pattern-match driven logic.

On the other hand, one of the criticisms of inspection by classic OOP theorists is the lack of formalisms and the ad hoc nature of what is being inspected. In a language such as Python, in which almost any aspect of an object can be reflected and directly accessed by external code, there are many different ways to test whether an object conforms to a particular protocol or not. For example, if asking ‘is this object a mutable sequence container?’, one can look for a base class of ‘list’, or one can look for a method named ‘__getitem__’. But note that although these tests may seem obvious, neither of them are correct, as one generates false negatives, and the other false positives.

The generally agreed-upon remedy is to standardize the tests, and group them into a formal arrangement. This is most easily done by associating with each class a set of standard testable properties, either via the inheritance mechanism or some other means. Each test carries with it a set of promises: it contains a promise about the general behavior of the class, and a promise as to what other class methods will be available.

This PEP proposes a particular strategy for organizing these tests known as Abstract Base Classes, or ABC. ABCs are simply Python classes that are added into an object’s inheritance tree to signal certain features of that object to an external inspector. Tests are done usingisinstance(),and the presence of a particular ABC means that the test has passed.

In addition, the ABCs define a minimal set of methods that establish the characteristic behavior of the type. Code that discriminates objects based on their ABC type can trust that those methods will always be present. Each of these methods are accompanied by an generalized abstract semantic definition that is described in the documentation for the ABC. These standard semantic definitions are not enforced, but are strongly recommended.

Like all other things in Python, these promises are in the nature of a friendly agreement, which in this case means that while the language does enforce some of the promises made in the ABC, it is up to the implementer of the concrete class to insure that the remaining ones are kept.

Specification

The specification follows the categories listed in the abstract:

  • A way to overloadisinstance()andissubclass().
  • A new moduleabcwhich serves as an “ABC support framework”. It defines a metaclass for use with ABCs and a decorator that can be used to define abstract methods.
  • Specific ABCs for containers and iterators, to be added to the collections module.

Overloadingisinstance()andissubclass()

During the development of this PEP and of its companion,PEP 3141,we repeatedly faced the choice between standardizing more, fine-grained ABCs or fewer, coarse-grained ones. For example, at one stage, PEP 3141 introduced the following stack of base classes used for complex numbers: MonoidUnderPlus, AdditiveGroup, Ring, Field, Complex (each derived from the previous). And the discussion mentioned several other algebraic categorizations that were left out: Algebraic, Transcendental, and IntegralDomain, and PrincipalIdealDomain. In earlier versions of the current PEP, we considered the use cases for separate classes like Set, ComposableSet, MutableSet, HashableSet, MutableComposableSet, HashableComposableSet.

The dilemma here is that we’d rather have fewer ABCs, but then what should a user do who needs a less refined ABC? Consider e.g. the plight of a mathematician who wants to define their own kind of Transcendental numbers, but also wants float and int to be considered Transcendental.PEP 3141originally proposed to patch float.__bases__ for that purpose, but there are some good reasons to keep the built-in types immutable (for one, they are shared between all Python interpreters running in the same address space, as is used by mod_ Python[16]).

Another example would be someone who wants to define a generic function (PEP 3124) for any sequence that has anappend()method. TheSequenceABC (see below) doesn’t promise theappend() method, whileMutableSequencerequires not onlyappend()but also various other mutating methods.

To solve these and similar dilemmas, the next section will propose a metaclass for use with ABCs that will allow us to add an ABC as a “virtual base class” (not the same concept as in C++) to any class, including to another ABC. This allows the standard library to define ABCsSequenceandMutableSequenceand register these as virtual base classes for built-in types likebasestring,tuple andlist,so that for example the following conditions are all true:

isinstance([],Sequence)
issubclass(list,Sequence)
issubclass(list,MutableSequence)
isinstance((),Sequence)
notissubclass(tuple,MutableSequence)
isinstance("",Sequence)
issubclass(bytearray,MutableSequence)

The primary mechanism proposed here is to allow overloading the built-in functionsisinstance()andissubclass().The overloading works as follows: The callisinstance(x,C)first checks whetherC.__instancecheck__exists, and if so, calls C.__instancecheck__(x)instead of its normal implementation. Similarly, the callissubclass(D,C)first checks whether C.__subclasscheck__exists, and if so, calls C.__subclasscheck__(D)instead of its normal implementation.

Note that the magic names are not__isinstance__and __issubclass__;this is because the reversal of the arguments could cause confusion, especially for theissubclass()overloader.

A prototype implementation of this is given in[12].

Here is an example with (naively simple) implementations of __instancecheck__and__subclasscheck__:

classABCMeta(type):

def__instancecheck__(cls,inst):
"""Implement isinstance(inst, cls)." ""
returnany(cls.__subclasscheck__(c)
forcin{type(inst),inst.__class__})

def__subclasscheck__(cls,sub):
"""Implement issubclass(sub, cls)." ""
candidates=cls.__dict__.get("__subclass__",set())|{cls}
returnany(cincandidatesforcinsub.mro())

classSequence(metaclass=ABCMeta):
__subclass__={list,tuple}

assertissubclass(list,Sequence)
assertissubclass(tuple,Sequence)

classAppendableSequence(Sequence):
__subclass__={list}

assertissubclass(list,AppendableSequence)
assertisinstance([],AppendableSequence)

assertnotissubclass(tuple,AppendableSequence)
assertnotisinstance((),AppendableSequence)

The next section proposes a full-fledged implementation.

TheabcModule: an ABC Support Framework

The new standard library moduleabc,written in pure Python, serves as an ABC support framework. It defines a metaclass ABCMetaand decorators@abstractmethodand @abstractproperty.A sample implementation is given by[13].

TheABCMetaclass overrides__instancecheck__and __subclasscheck__and defines aregistermethod. The registermethod takes one argument, which must be a class; after the callB.register(C),the callissubclass(C,B)will return True, by virtue ofB.__subclasscheck__(C)returning True. Also,isinstance(x,B)is equivalent toissubclass(x.__class__, B)orissubclass(type(x),B).(It is possibletype(x)and x.__class__are not the same object, e.g. when x is a proxy object.)

These methods are intended to be called on classes whose metaclass is (derived from)ABCMeta;for example:

fromabcimportABCMeta

classMyABC(metaclass=ABCMeta):
pass

MyABC.register(tuple)

assertissubclass(tuple,MyABC)
assertisinstance((),MyABC)

The last two asserts are equivalent to the following two:

assertMyABC.__subclasscheck__(tuple)
assertMyABC.__instancecheck__(())

Of course, you can also directly subclass MyABC:

classMyClass(MyABC):
pass

assertissubclass(MyClass,MyABC)
assertisinstance(MyClass(),MyABC)

Also, of course, a tuple is not aMyClass:

assertnotissubclass(tuple,MyClass)
assertnotisinstance((),MyClass)

You can register another class as a subclass ofMyClass:

MyClass.register(list)

assertissubclass(list,MyClass)
assertissubclass(list,MyABC)

You can also register another ABC:

classAnotherClass(metaclass=ABCMeta):
pass

AnotherClass.register(basestring)

MyClass.register(AnotherClass)

assertisinstance(str,MyABC)

That last assert requires tracing the following superclass-subclass relationships:

MyABC->MyClass(usingregularsubclassing)
MyClass->AnotherClass(usingregistration)
AnotherClass->basestring(usingregistration)
basestring->str(usingregularsubclassing)

Theabcmodule also defines a new decorator,@abstractmethod, to be used to declare abstract methods. A class containing at least one method declared with this decorator that hasn’t been overridden yet cannot be instantiated. Such methods may be called from the overriding method in the subclass (usingsuperor direct invocation). For example:

fromabcimportABCMeta,abstractmethod

classA(metaclass=ABCMeta):
@abstractmethod
deffoo(self):pass

A()# raises TypeError

classB(A):
pass

B()# raises TypeError

classC(A):
deffoo(self):print(42)

C()# works

Note:The@abstractmethoddecorator should only be used inside a class body, and only for classes whose metaclass is (derived from)ABCMeta.Dynamically adding abstract methods to a class, or attempting to modify the abstraction status of a method or class once it is created, are not supported. The@abstractmethodonly affects subclasses derived using regular inheritance; “virtual subclasses” registered with theregister()method are not affected.

Implementation:The@abstractmethoddecorator sets the function attribute__isabstractmethod__to the valueTrue. TheABCMeta.__new__method computes the type attribute __abstractmethods__as the set of all method names that have an __isabstractmethod__attribute whose value is true. It does this by combining the__abstractmethods__attributes of the base classes, adding the names of all methods in the new class dict that have a true__isabstractmethod__attribute, and removing the names of all methods in the new class dict that don’t have a true __isabstractmethod__attribute. If the resulting __abstractmethods__set is non-empty, the class is considered abstract, and attempts to instantiate it will raiseTypeError. (If this were implemented in CPython, an internal flag Py_TPFLAGS_ABSTRACTcould be used to speed up this check[6].)

Discussion:Unlike Java’s abstract methods or C++’s pure abstract methods, abstract methods as defined here may have an implementation. This implementation can be called via thesupermechanism from the class that overrides it. This could be useful as an end-point for a super-call in framework using cooperative multiple-inheritance[7], [8].

A second decorator,@abstractproperty,is defined in order to define abstract data attributes. Its implementation is a subclass of the built-inpropertyclass that adds an__isabstractmethod__ attribute:

classabstractproperty(property):
__isabstractmethod__=True

It can be used in two ways:

classC(metaclass=ABCMeta):

# A read-only property:

@abstractproperty
defreadonly(self):
returnself.__x

# A read-write property (cannot use decorator syntax):

defgetx(self):
returnself.__x
defsetx(self,value):
self.__x=value
x=abstractproperty(getx,setx)

Similar to abstract methods, a subclass inheriting an abstract property (declared using either the decorator syntax or the longer form) cannot be instantiated unless it overrides that abstract property with a concrete property.

ABCs for Containers and Iterators

Thecollectionsmodule will define ABCs necessary and sufficient to work with sets, mappings, sequences, and some helper types such as iterators and dictionary views. All ABCs have the above-mentioned ABCMetaas their metaclass.

The ABCs provide implementations of their abstract methods that are technically valid but fairly useless; e.g.__hash__returns 0, and __iter__returns an empty iterator. In general, the abstract methods represent the behavior of an empty container of the indicated type.

Some ABCs also provide concrete (i.e. non-abstract) methods; for example, theIteratorclass has an__iter__method returning itself, fulfilling an important invariant of iterators (which in Python 2 has to be implemented anew by each iterator class). These ABCs can be considered “mix-in” classes.

No ABCs defined in the PEP override__init__,__new__, __str__or__repr__.Defining a standard constructor signature would unnecessarily constrain custom container types, for example Patricia trees or gdbm files. Defining a specific string representation for a collection is similarly left up to individual implementations.

Note:There are no ABCs for ordering operations (__lt__, __le__,__ge__,__gt__). Defining these in a base class (abstract or not) runs into problems with the accepted type for the second operand. For example, if classOrderingdefined __lt__,one would assume that for anyOrderinginstancesx andy,x<ywould be defined (even if it just defines a partial ordering). But this cannot be the case: If bothlistand strderived fromOrdering,this would imply that[1,2]< (1,2)should be defined (and presumably return False), while in fact (in Python 3000!) such “mixed-mode comparisons” operations are explicitly forbidden and raiseTypeError.SeePEP 3100and[14] for more information. (This is a special case of a more general issue with operations that take another argument of the same type).

One Trick Ponies

These abstract classes represent single methods like__iter__or __len__.

Hashable
The base class for classes defining__hash__.The __hash__method should return an integer. The abstract __hash__method always returns 0, which is a valid (albeit inefficient) implementation.Invariant:If classesC1and C2both derive fromHashable,the conditiono1==o2 must implyhash(o1)==hash(o2)for all instanceso1of C1and all instanceso2ofC2.In other words, two objects should never compare equal if they have different hash values.

Another constraint is that hashable objects, once created, should never change their value (as compared by==) or their hash value. If a class cannot guarantee this, it should not derive fromHashable;if it cannot guarantee this for certain instances,__hash__for those instances should raise a TypeErrorexception.

Note:being an instance of this class does not imply that an object is immutable; e.g. a tuple containing a list as a member is not immutable; its__hash__method raisesTypeError. (This is because it recursively tries to compute the hash of each member; if a member is unhashable it raisesTypeError.)

Iterable
The base class for classes defining__iter__.The __iter__method should always return an instance of Iterator(see below). The abstract__iter__method returns an empty iterator.
Iterator
The base class for classes defining__next__.This derives fromIterable.The abstract__next__method raises StopIteration.The concrete__iter__method returns self.Note the distinction betweenIterableand Iterator:anIterablecan be iterated over, i.e. supports the__iter__methods; anIteratoris what the built-in functioniter()returns, i.e. supports the__next__ method.
Sized
The base class for classes defining__len__.The__len__ method should return anInteger(see “Numbers” below) >= 0. The abstract__len__method returns 0.Invariant:If a classCderives fromSizedas well as fromIterable, the invariantsum(1forxinc)==len(c)should hold for any instancecofC.
Container
The base class for classes defining__contains__.The __contains__method should return abool.The abstract __contains__method returnsFalse.Invariant:If a classCderives fromContaineras well as from Iterable,then(xincforxinc)should be a generator yielding only True values for any instancecofC.

Open issues:Conceivably, instead of using the ABCMeta metaclass, these classes could override__instancecheck__and __subclasscheck__to check for the presence of the applicable special method; for example:

classSized(metaclass=ABCMeta):
@abstractmethod
def__hash__(self):
return0
@classmethod
def__instancecheck__(cls,x):
returnhasattr(x,"__len__")
@classmethod
def__subclasscheck__(cls,C):
returnhasattr(C,"__bases__")andhasattr(C,"__len__")

This has the advantage of not requiring explicit registration. However, the semantics are hard to get exactly right given the confusing semantics of instance attributes vs. class attributes, and that a class is an instance of its metaclass; the check for__bases__is only an approximation of the desired semantics.Strawman:Let’s do it, but let’s arrange it in such a way that the registration API also works.

Sets

These abstract classes represent read-only sets and mutable sets. The most fundamental set operation is the membership test, written asx insand implemented bys.__contains__(x).This operation is already defined by theContainerclass defined above. Therefore, we define a set as a sized, iterable container for which certain invariants from mathematical set theory hold.

The built-in typesetderives fromMutableSet.The built-in typefrozensetderives fromSetandHashable.

Set
This is a sized, iterable container, i.e., a subclass of Sized,IterableandContainer.Not every subclass of those three classes is a set though! Sets have the additional invariant that each element occurs only once (as can be determined by iteration), and in addition sets define concrete operators that implement the inequality operations as subset/superset tests. In general, the invariants for finite sets in mathematics hold.[11]

Sets with different implementations can be compared safely, (usually) efficiently and correctly using the mathematical definitions of the subset/supeset operations for finite sets. The ordering operations have concrete implementations; subclasses may override these for speed but should maintain the semantics. BecauseSetderives fromSized,__eq__may take a shortcut and returnFalseimmediately if two sets of unequal length are compared. Similarly,__le__may returnFalse immediately if the first set has more members than the second set. Note that set inclusion implements only a partial ordering; e.g.{1,2}and{1,3}are not ordered (all three of <,==and>returnFalsefor these arguments). Sets cannot be ordered relative to mappings or sequences, but they can be compared to those for equality (and then they always compare unequal).

This class also defines concrete operators to compute union, intersection, symmetric and asymmetric difference, respectively __or__,__and__,__xor__and__sub__.These operators should return instances ofSet.The default implementations call the overridable class method _from_iterable()with an iterable argument. This factory method’s default implementation returns afrozensetinstance; it may be overridden to return another appropriateSet subclass.

Finally, this class defines a concrete method_hashwhich computes the hash value from the elements. Hashable subclasses of Setcan implement__hash__by calling_hashor they can reimplement the same algorithm more efficiently; but the algorithm implemented should be the same. Currently the algorithm is fully specified only by the source code[15].

Note:theissubsetandissupersetmethods found on the set type in Python 2 are not supported, as these are mostly just aliases for__le__and__ge__.

MutableSet
This is a subclass ofSetimplementing additional operations to add and remove elements. The supported methods have the semantics known from thesettype in Python 2 (except for discard,which is modeled after Java):
.add(x)
Abstract method returning aboolthat adds the element xif it isn’t already in the set. It should return Trueifxwas added,Falseif it was already there. The abstract implementation raises NotImplementedError.
.discard(x)
Abstract method returning aboolthat removes the element xif present. It should returnTrueif the element was present andFalseif it wasn’t. The abstract implementation raisesNotImplementedError.
.pop()
Concrete method that removes and returns an arbitrary item. If the set is empty, it raisesKeyError.The default implementation removes the first item returned by the set’s iterator.
.toggle(x)
Concrete method returning aboolthat adds x to the set if it wasn’t there, but removes it if it was there. It should returnTrueifxwas added,Falseif it was removed.
.clear()
Concrete method that empties the set. The default implementation repeatedly callsself.pop()until KeyErroris caught. (Note:this is likely much slower than simply creating a new set, even if an implementation overrides it with a faster approach; but in some cases object identity is important.)

This also supports the in-place mutating operations|=, &=,^=,-=.These are concrete methods whose right operand can be an arbitraryIterable,except for&=,whose right operand must be aContainer.This ABC does not provide the named methods present on the built-in concretesettype that perform (almost) the same operations.

Mappings

These abstract classes represent read-only mappings and mutable mappings. TheMappingclass represents the most common read-only mapping API.

The built-in typedictderives fromMutableMapping.

Mapping
A subclass ofContainer,IterableandSized.The keys of a mapping naturally form a set. The (key, value) pairs (which must be tuples) are also referred to as items. The items also form a set. Methods:
.__getitem__(key)
Abstract method that returns the value corresponding to key,or raisesKeyError.The implementation always raisesKeyError.
.get(key,default=None)
Concrete method returningself[key]if this does not raise KeyError,and thedefaultvalue if it does.
.__contains__(key)
Concrete method returningTrueifself[key]does not raiseKeyError,andFalseif it does.
.__len__()
Abstract method returning the number of distinct keys (i.e., the length of the key set).
.__iter__()
Abstract method returning each key in the key set exactly once.
.keys()
Concrete method returning the key set as aSet.The default concrete implementation returns a “view” on the key set (meaning if the underlying mapping is modified, the view’s value changes correspondingly); subclasses are not required to return a view but they should return aSet.
.items()
Concrete method returning the items as aSet.The default concrete implementation returns a “view” on the item set; subclasses are not required to return a view but they should return aSet.
.values()
Concrete method returning the values as a sized, iterable container (not a set!). The default concrete implementation returns a “view” on the values of the mapping; subclasses are not required to return a view but they should return a sized, iterable container.

The following invariants should hold for any mappingm:

len(m.values())==len(m.keys())==len(m.items())==len(m)
[valueforvalueinm.values()]==[m[key]forkeyinm.keys()]
[itemforiteminm.items()]==[(key,m[key])forkeyinm.keys()]

i.e. iterating over the items, keys and values should return results in the same order.

MutableMapping
A subclass ofMappingthat also implements some standard mutating methods. Abstract methods include__setitem__, __delitem__.Concrete methods includepop,popitem, clear,update.Note:setdefaultisnotincluded. Open issues:Write out the specs for the methods.

Sequences

These abstract classes represent read-only sequences and mutable sequences.

The built-inlistandbytestypes derive from MutableSequence.The built-intupleandstrtypes derive fromSequenceandHashable.

Sequence
A subclass ofIterable,Sized,Container.It defines a new abstract method__getitem__that has a somewhat complicated signature: when called with an integer, it returns an element of the sequence or raisesIndexError;when called with asliceobject, it returns anotherSequence.The concrete __iter__method iterates over the elements using __getitem__with integer arguments 0, 1, and so on, until IndexErroris raised. The length should be equal to the number of values returned by the iterator.

Open issues:Other candidate methods, which can all have default concrete implementations that only depend on__len__ and__getitem__with an integer argument:__reversed__, index,count,__add__,__mul__.

MutableSequence
A subclass ofSequenceadding some standard mutating methods. Abstract mutating methods:__setitem__(for integer indices as well as slices),__delitem__(ditto),insert.Concrete mutating methods:append,reverse,extend,pop, remove.Concrete mutating operators:+=,*=(these mutate the object in place).Note:this does not define sort()– that is only required to exist on genuinelist instances.

Strings

Python 3000 will likely have at least two built-in string types: byte strings (bytes), deriving fromMutableSequence,and (Unicode) character strings (str), deriving fromSequenceand Hashable.

Open issues:define the base interfaces for these so alternative implementations and subclasses know what they are in for. This may be the subject of a new PEP or PEPs (PEP 358should be co-opted for the bytestype).

ABCs vs. Alternatives

In this section I will attempt to compare and contrast ABCs to other approaches that have been proposed.

ABCs vs. Duck Typing

Does the introduction of ABCs mean the end of Duck Typing? I don’t think so. Python will not require that a class derives from BasicMappingorSequencewhen it defines a__getitem__ method, nor will thex[y]syntax require thatxis an instance of either ABC. You will still be able to assign any “file-like” object tosys.stdout,as long as it has awritemethod.

Of course, there will be some carrots to encourage users to derive from the appropriate base classes; these vary from default implementations for certain functionality to an improved ability to distinguish between mappings and sequences. But there are no sticks. Ifhasattr(x,"__len__" )works for you, great! ABCs are intended to solve problems that don’t have a good solution at all in Python 2, such as distinguishing between mappings and sequences.

ABCs vs. Generic Functions

ABCs are compatible with Generic Functions (GFs). For example, my own Generic Functions implementation[4]uses the classes (types) of the arguments as the dispatch key, allowing derived classes to override base classes. Since (from Python’s perspective) ABCs are quite ordinary classes, using an ABC in the default implementation for a GF can be quite appropriate. For example, if I have an overloaded prettyprintfunction, it would make total sense to define pretty-printing of sets like this:

@prettyprint.register(Set)
defpp_set(s):
return"{"+...+"}"# Details left as an exercise

and implementations for specific subclasses of Set could be added easily.

I believe ABCs also won’t present any problems for RuleDispatch, Phillip Eby’s GF implementation in PEAK[5].

Of course, GF proponents might claim that GFs (and concrete, or implementation, classes) are all you need. But even they will not deny the usefulness of inheritance; and one can easily consider the ABCs proposed in this PEP as optional implementation base classes; there is no requirement that all user-defined mappings derive from BasicMapping.

ABCs vs. Interfaces

ABCs are not intrinsically incompatible with Interfaces, but there is considerable overlap. For now, I’ll leave it to proponents of Interfaces to explain why Interfaces are better. I expect that much of the work that went into e.g. defining the various shades of “mapping-ness” and the nomenclature could easily be adapted for a proposal to use Interfaces instead of ABCs.

“Interfaces” in this context refers to a set of proposals for additional metadata elements attached to a class which are not part of the regular class hierarchy, but do allow for certain types of inheritance testing.

Such metadata would be designed, at least in some proposals, so as to be easily mutable by an application, allowing application writers to override the normal classification of an object.

The drawback to this idea of attaching mutable metadata to a class is that classes are shared state, and mutating them may lead to conflicts of intent. Additionally, the need to override the classification of an object can be done more cleanly using generic functions: In the simplest case, one can define a “category membership” generic function that simply returns False in the base implementation, and then provide overrides that return True for any classes of interest.

References

[2] Incomplete implementation prototype, by GvR (https://web.archive.org/web/20170223133820/http://svn. Python.org/view/sandbox/trunk/abc/)

[3] Possible Python 3K Class Tree?, wiki page created by Bill Janssen (https://wiki. Python.org/moin/AbstractBaseClasses)

[9] Partial order, in Wikipedia (https://en.wikipedia.org/wiki/Partial_order)

[10] Total order, in Wikipedia (https://en.wikipedia.org/wiki/Total_order)


Source:https://github / Python /peps/blob/main/peps/pep-3119.rst

Last modified:2023-09-09 17:39:29 GMT