• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Copyright 2007 Google, Inc. All Rights Reserved.
2# Licensed to PSF under a Contributor Agreement.
3
4"""Abstract Base Classes (ABCs) according to PEP 3119."""
5
6
7def abstractmethod(funcobj):
8    """A decorator indicating abstract methods.
9
10    Requires that the metaclass is ABCMeta or derived from it.  A
11    class that has a metaclass derived from ABCMeta cannot be
12    instantiated unless all of its abstract methods are overridden.
13    The abstract methods can be called using any of the normal
14    'super' call mechanisms.
15
16    Usage:
17
18        class C(metaclass=ABCMeta):
19            @abstractmethod
20            def my_abstract_method(self, ...):
21                ...
22    """
23    funcobj.__isabstractmethod__ = True
24    return funcobj
25
26
27class abstractclassmethod(classmethod):
28    """A decorator indicating abstract classmethods.
29
30    Similar to abstractmethod.
31
32    Usage:
33
34        class C(metaclass=ABCMeta):
35            @abstractclassmethod
36            def my_abstract_classmethod(cls, ...):
37                ...
38
39    'abstractclassmethod' is deprecated. Use 'classmethod' with
40    'abstractmethod' instead.
41    """
42
43    __isabstractmethod__ = True
44
45    def __init__(self, callable):
46        callable.__isabstractmethod__ = True
47        super().__init__(callable)
48
49
50class abstractstaticmethod(staticmethod):
51    """A decorator indicating abstract staticmethods.
52
53    Similar to abstractmethod.
54
55    Usage:
56
57        class C(metaclass=ABCMeta):
58            @abstractstaticmethod
59            def my_abstract_staticmethod(...):
60                ...
61
62    'abstractstaticmethod' is deprecated. Use 'staticmethod' with
63    'abstractmethod' instead.
64    """
65
66    __isabstractmethod__ = True
67
68    def __init__(self, callable):
69        callable.__isabstractmethod__ = True
70        super().__init__(callable)
71
72
73class abstractproperty(property):
74    """A decorator indicating abstract properties.
75
76    Requires that the metaclass is ABCMeta or derived from it.  A
77    class that has a metaclass derived from ABCMeta cannot be
78    instantiated unless all of its abstract properties are overridden.
79    The abstract properties can be called using any of the normal
80    'super' call mechanisms.
81
82    Usage:
83
84        class C(metaclass=ABCMeta):
85            @abstractproperty
86            def my_abstract_property(self):
87                ...
88
89    This defines a read-only property; you can also define a read-write
90    abstract property using the 'long' form of property declaration:
91
92        class C(metaclass=ABCMeta):
93            def getx(self): ...
94            def setx(self, value): ...
95            x = abstractproperty(getx, setx)
96
97    'abstractproperty' is deprecated. Use 'property' with 'abstractmethod'
98    instead.
99    """
100
101    __isabstractmethod__ = True
102
103
104try:
105    from _abc import (get_cache_token, _abc_init, _abc_register,
106                      _abc_instancecheck, _abc_subclasscheck, _get_dump,
107                      _reset_registry, _reset_caches)
108except ImportError:
109    from _py_abc import ABCMeta, get_cache_token
110    ABCMeta.__module__ = 'abc'
111else:
112    class ABCMeta(type):
113        """Metaclass for defining Abstract Base Classes (ABCs).
114
115        Use this metaclass to create an ABC.  An ABC can be subclassed
116        directly, and then acts as a mix-in class.  You can also register
117        unrelated concrete classes (even built-in classes) and unrelated
118        ABCs as 'virtual subclasses' -- these and their descendants will
119        be considered subclasses of the registering ABC by the built-in
120        issubclass() function, but the registering ABC won't show up in
121        their MRO (Method Resolution Order) nor will method
122        implementations defined by the registering ABC be callable (not
123        even via super()).
124        """
125        def __new__(mcls, name, bases, namespace, **kwargs):
126            cls = super().__new__(mcls, name, bases, namespace, **kwargs)
127            _abc_init(cls)
128            return cls
129
130        def register(cls, subclass):
131            """Register a virtual subclass of an ABC.
132
133            Returns the subclass, to allow usage as a class decorator.
134            """
135            return _abc_register(cls, subclass)
136
137        def __instancecheck__(cls, instance):
138            """Override for isinstance(instance, cls)."""
139            return _abc_instancecheck(cls, instance)
140
141        def __subclasscheck__(cls, subclass):
142            """Override for issubclass(subclass, cls)."""
143            return _abc_subclasscheck(cls, subclass)
144
145        def _dump_registry(cls, file=None):
146            """Debug helper to print the ABC registry."""
147            print(f"Class: {cls.__module__}.{cls.__qualname__}", file=file)
148            print(f"Inv. counter: {get_cache_token()}", file=file)
149            (_abc_registry, _abc_cache, _abc_negative_cache,
150             _abc_negative_cache_version) = _get_dump(cls)
151            print(f"_abc_registry: {_abc_registry!r}", file=file)
152            print(f"_abc_cache: {_abc_cache!r}", file=file)
153            print(f"_abc_negative_cache: {_abc_negative_cache!r}", file=file)
154            print(f"_abc_negative_cache_version: {_abc_negative_cache_version!r}",
155                  file=file)
156
157        def _abc_registry_clear(cls):
158            """Clear the registry (for debugging or testing)."""
159            _reset_registry(cls)
160
161        def _abc_caches_clear(cls):
162            """Clear the caches (for debugging or testing)."""
163            _reset_caches(cls)
164
165
166class ABC(metaclass=ABCMeta):
167    """Helper class that provides a standard way to create an ABC using
168    inheritance.
169    """
170    __slots__ = ()
171