开发者

Comprehensive list of Python protocols/interfaces

Lately, I was looking at some Python idioms. I found many descriptions of protocols used in Python, such as the ordering (__cmp__, ...) or generators. Besides, there are also methods like 开发者_如何转开发__hash__ which are defined for every object (I suppose).

After some search on the internet, I haven't found a comprehensive list of these protocols and methods. Can anyone give me some pointers URLs?


Your best reference is always going to be the Python Online Documentation, specifically the section on Special method names.

The interactive Python interpretor is a very useful tool, too. Try some of these:

>>> dir(object)
['__class__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
>>> help(object.__class__)

>>> help(object.__hash__)

>>> help(hash)


By convention, protocols are groups of special methods that describe common behaviors. You can infer protocols from the abstract methods of the collections.abc module (Python 3.3+); see also the docs. Automate this listing with the following:

Given

import abc

import collections as ct

Code

def get_protocols(source=ct.abc):
    """Return a dict of protocols from `collections.abc`."""
    d = {}

    for objname in dir(source):

        if objname.startswith("_"):
            continue
        obj = getattr(source, objname)
        abmethods = sorted(obj.__abstractmethods__)
        if not abmethods:
            continue    
        d[objname] = abmethods        
    return d

Demo

get_protocols()

Output

{
 'AsyncGenerator': ['asend', 'athrow'], 
 'AsyncIterable': ['__aiter__'], 
 'AsyncIterator': ['__anext__'],
 'Awaitable': ['__await__'], 
 'ByteString': ['__getitem__', '__len__'],
 'Callable': ['__call__'], 
 'Collection': ['__contains__', '__iter__', '__len__'], 
 'Container': ['__contains__'], 
 'Coroutine': ['__await__', 'send', 'throw'], 
 'Generator': ['send', 'throw'], 
 'Hashable': ['__hash__'], 
 'Iterable': ['__iter__'], 
 'Iterator': ['__next__'],
 'Mapping': ['__getitem__', '__iter__', '__len__'], 
 'MutableMapping': ['__delitem__', '__getitem__', '__iter__', '__len__', '__setitem__'],
 'MutableSequence': ['__delitem__', '__getitem__', '__len__', '__setitem__', 'insert'], 
 'MutableSet': ['__contains__', '__iter__', '__len__', 'add', 'discard'],
 'Reversible': ['__iter__', '__reversed__'], 
 'Sequence': ['__getitem__', '__len__'], 
 'Set': ['__contains__', '__iter__', '__len__'], 
 'Sized': ['__len__']
}

NOTE: When sub-classing, these are (required) abstract methods that do not include the mixin methods. Example: sub-classing collections.abc.Mappings will provide methods .keys(), .values(), .items() (no listed) once the protocol is implemented.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜