ÿØÿà JFIF    ÿÛ „ ( %!1!%*+...983,7(-.- lib64/python3.8/abc.py000064400000010611152343140120010327 0ustar00# Copyright 2007 Google, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. """Abstract Base Classes (ABCs) according to PEP 3119.""" def abstractmethod(funcobj): """A decorator indicating abstract methods. Requires that the metaclass is ABCMeta or derived from it. A class that has a metaclass derived from ABCMeta cannot be instantiated unless all of its abstract methods are overridden. The abstract methods can be called using any of the normal 'super' call mechanisms. abstractmethod() may be used to declare abstract methods for properties and descriptors. Usage: class C(metaclass=ABCMeta): @abstractmethod def my_abstract_method(self, ...): ... """ funcobj.__isabstractmethod__ = True return funcobj class abstractclassmethod(classmethod): """A decorator indicating abstract classmethods. Deprecated, use 'classmethod' with 'abstractmethod' instead. """ __isabstractmethod__ = True def __init__(self, callable): callable.__isabstractmethod__ = True super().__init__(callable) class abstractstaticmethod(staticmethod): """A decorator indicating abstract staticmethods. Deprecated, use 'staticmethod' with 'abstractmethod' instead. """ __isabstractmethod__ = True def __init__(self, callable): callable.__isabstractmethod__ = True super().__init__(callable) class abstractproperty(property): """A decorator indicating abstract properties. Deprecated, use 'property' with 'abstractmethod' instead. """ __isabstractmethod__ = True try: from _abc import (get_cache_token, _abc_init, _abc_register, _abc_instancecheck, _abc_subclasscheck, _get_dump, _reset_registry, _reset_caches) except ImportError: from _py_abc import ABCMeta, get_cache_token ABCMeta.__module__ = 'abc' else: class ABCMeta(type): """Metaclass for defining Abstract Base Classes (ABCs). Use this metaclass to create an ABC. An ABC can be subclassed directly, and then acts as a mix-in class. You can also register unrelated concrete classes (even built-in classes) and unrelated ABCs as 'virtual subclasses' -- these and their descendants will be considered subclasses of the registering ABC by the built-in issubclass() function, but the registering ABC won't show up in their MRO (Method Resolution Order) nor will method implementations defined by the registering ABC be callable (not even via super()). """ def __new__(mcls, name, bases, namespace, **kwargs): cls = super().__new__(mcls, name, bases, namespace, **kwargs) _abc_init(cls) return cls def register(cls, subclass): """Register a virtual subclass of an ABC. Returns the subclass, to allow usage as a class decorator. """ return _abc_register(cls, subclass) def __instancecheck__(cls, instance): """Override for isinstance(instance, cls).""" return _abc_instancecheck(cls, instance) def __subclasscheck__(cls, subclass): """Override for issubclass(subclass, cls).""" return _abc_subclasscheck(cls, subclass) def _dump_registry(cls, file=None): """Debug helper to print the ABC registry.""" print(f"Class: {cls.__module__}.{cls.__qualname__}", file=file) print(f"Inv. counter: {get_cache_token()}", file=file) (_abc_registry, _abc_cache, _abc_negative_cache, _abc_negative_cache_version) = _get_dump(cls) print(f"_abc_registry: {_abc_registry!r}", file=file) print(f"_abc_cache: {_abc_cache!r}", file=file) print(f"_abc_negative_cache: {_abc_negative_cache!r}", file=file) print(f"_abc_negative_cache_version: {_abc_negative_cache_version!r}", file=file) def _abc_registry_clear(cls): """Clear the registry (for debugging or testing).""" _reset_registry(cls) def _abc_caches_clear(cls): """Clear the caches (for debugging or testing).""" _reset_caches(cls) class ABC(metaclass=ABCMeta): """Helper class that provides a standard way to create an ABC using inheritance. """ __slots__ = () usr/lib64/python3.6/abc.py000064400000021027152343142610011147 0ustar00# Copyright 2007 Google, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. """Abstract Base Classes (ABCs) according to PEP 3119.""" from _weakrefset import WeakSet def abstractmethod(funcobj): """A decorator indicating abstract methods. Requires that the metaclass is ABCMeta or derived from it. A class that has a metaclass derived from ABCMeta cannot be instantiated unless all of its abstract methods are overridden. The abstract methods can be called using any of the normal 'super' call mechanisms. Usage: class C(metaclass=ABCMeta): @abstractmethod def my_abstract_method(self, ...): ... """ funcobj.__isabstractmethod__ = True return funcobj class abstractclassmethod(classmethod): """ A decorator indicating abstract classmethods. Similar to abstractmethod. Usage: class C(metaclass=ABCMeta): @abstractclassmethod def my_abstract_classmethod(cls, ...): ... 'abstractclassmethod' is deprecated. Use 'classmethod' with 'abstractmethod' instead. """ __isabstractmethod__ = True def __init__(self, callable): callable.__isabstractmethod__ = True super().__init__(callable) class abstractstaticmethod(staticmethod): """ A decorator indicating abstract staticmethods. Similar to abstractmethod. Usage: class C(metaclass=ABCMeta): @abstractstaticmethod def my_abstract_staticmethod(...): ... 'abstractstaticmethod' is deprecated. Use 'staticmethod' with 'abstractmethod' instead. """ __isabstractmethod__ = True def __init__(self, callable): callable.__isabstractmethod__ = True super().__init__(callable) class abstractproperty(property): """ A decorator indicating abstract properties. Requires that the metaclass is ABCMeta or derived from it. A class that has a metaclass derived from ABCMeta cannot be instantiated unless all of its abstract properties are overridden. The abstract properties can be called using any of the normal 'super' call mechanisms. Usage: class C(metaclass=ABCMeta): @abstractproperty def my_abstract_property(self): ... This defines a read-only property; you can also define a read-write abstract property using the 'long' form of property declaration: class C(metaclass=ABCMeta): def getx(self): ... def setx(self, value): ... x = abstractproperty(getx, setx) 'abstractproperty' is deprecated. Use 'property' with 'abstractmethod' instead. """ __isabstractmethod__ = True class ABCMeta(type): """Metaclass for defining Abstract Base Classes (ABCs). Use this metaclass to create an ABC. An ABC can be subclassed directly, and then acts as a mix-in class. You can also register unrelated concrete classes (even built-in classes) and unrelated ABCs as 'virtual subclasses' -- these and their descendants will be considered subclasses of the registering ABC by the built-in issubclass() function, but the registering ABC won't show up in their MRO (Method Resolution Order) nor will method implementations defined by the registering ABC be callable (not even via super()). """ # A global counter that is incremented each time a class is # registered as a virtual subclass of anything. It forces the # negative cache to be cleared before its next use. # Note: this counter is private. Use `abc.get_cache_token()` for # external code. _abc_invalidation_counter = 0 def __new__(mcls, name, bases, namespace, **kwargs): cls = super().__new__(mcls, name, bases, namespace, **kwargs) # Compute set of abstract method names abstracts = {name for name, value in namespace.items() if getattr(value, "__isabstractmethod__", False)} for base in bases: for name in getattr(base, "__abstractmethods__", set()): value = getattr(cls, name, None) if getattr(value, "__isabstractmethod__", False): abstracts.add(name) cls.__abstractmethods__ = frozenset(abstracts) # Set up inheritance registry cls._abc_registry = WeakSet() cls._abc_cache = WeakSet() cls._abc_negative_cache = WeakSet() cls._abc_negative_cache_version = ABCMeta._abc_invalidation_counter return cls def register(cls, subclass): """Register a virtual subclass of an ABC. Returns the subclass, to allow usage as a class decorator. """ if not isinstance(subclass, type): raise TypeError("Can only register classes") if issubclass(subclass, cls): return subclass # Already a subclass # Subtle: test for cycles *after* testing for "already a subclass"; # this means we allow X.register(X) and interpret it as a no-op. if issubclass(cls, subclass): # This would create a cycle, which is bad for the algorithm below raise RuntimeError("Refusing to create an inheritance cycle") cls._abc_registry.add(subclass) ABCMeta._abc_invalidation_counter += 1 # Invalidate negative cache return subclass def _dump_registry(cls, file=None): """Debug helper to print the ABC registry.""" print("Class: %s.%s" % (cls.__module__, cls.__qualname__), file=file) print("Inv.counter: %s" % ABCMeta._abc_invalidation_counter, file=file) for name in sorted(cls.__dict__): if name.startswith("_abc_"): value = getattr(cls, name) if isinstance(value, WeakSet): value = set(value) print("%s: %r" % (name, value), file=file) def __instancecheck__(cls, instance): """Override for isinstance(instance, cls).""" # Inline the cache checking subclass = instance.__class__ if subclass in cls._abc_cache: return True subtype = type(instance) if subtype is subclass: if (cls._abc_negative_cache_version == ABCMeta._abc_invalidation_counter and subclass in cls._abc_negative_cache): return False # Fall back to the subclass check. return cls.__subclasscheck__(subclass) return any(cls.__subclasscheck__(c) for c in {subclass, subtype}) def __subclasscheck__(cls, subclass): """Override for issubclass(subclass, cls).""" # Check cache if subclass in cls._abc_cache: return True # Check negative cache; may have to invalidate if cls._abc_negative_cache_version < ABCMeta._abc_invalidation_counter: # Invalidate the negative cache cls._abc_negative_cache = WeakSet() cls._abc_negative_cache_version = ABCMeta._abc_invalidation_counter elif subclass in cls._abc_negative_cache: return False # Check the subclass hook ok = cls.__subclasshook__(subclass) if ok is not NotImplemented: assert isinstance(ok, bool) if ok: cls._abc_cache.add(subclass) else: cls._abc_negative_cache.add(subclass) return ok # Check if it's a direct subclass if cls in getattr(subclass, '__mro__', ()): cls._abc_cache.add(subclass) return True # Check if it's a subclass of a registered class (recursive) for rcls in cls._abc_registry: if issubclass(subclass, rcls): cls._abc_cache.add(subclass) return True # Check if it's a subclass of a subclass (recursive) for scls in cls.__subclasses__(): if issubclass(subclass, scls): cls._abc_cache.add(subclass) return True # No dice; update negative cache cls._abc_negative_cache.add(subclass) return False class ABC(metaclass=ABCMeta): """Helper class that provides a standard way to create an ABC using inheritance. """ pass def get_cache_token(): """Returns the current ABC cache token. The token is an opaque object (supporting equality testing) identifying the current version of the ABC cache for virtual subclasses. The token changes with every call to ``register()`` on any ABC. """ return ABCMeta._abc_invalidation_counter lib64/python3.6/abc.py000064400000021027152343377400010345 0ustar00# Copyright 2007 Google, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. """Abstract Base Classes (ABCs) according to PEP 3119.""" from _weakrefset import WeakSet def abstractmethod(funcobj): """A decorator indicating abstract methods. Requires that the metaclass is ABCMeta or derived from it. A class that has a metaclass derived from ABCMeta cannot be instantiated unless all of its abstract methods are overridden. The abstract methods can be called using any of the normal 'super' call mechanisms. Usage: class C(metaclass=ABCMeta): @abstractmethod def my_abstract_method(self, ...): ... """ funcobj.__isabstractmethod__ = True return funcobj class abstractclassmethod(classmethod): """ A decorator indicating abstract classmethods. Similar to abstractmethod. Usage: class C(metaclass=ABCMeta): @abstractclassmethod def my_abstract_classmethod(cls, ...): ... 'abstractclassmethod' is deprecated. Use 'classmethod' with 'abstractmethod' instead. """ __isabstractmethod__ = True def __init__(self, callable): callable.__isabstractmethod__ = True super().__init__(callable) class abstractstaticmethod(staticmethod): """ A decorator indicating abstract staticmethods. Similar to abstractmethod. Usage: class C(metaclass=ABCMeta): @abstractstaticmethod def my_abstract_staticmethod(...): ... 'abstractstaticmethod' is deprecated. Use 'staticmethod' with 'abstractmethod' instead. """ __isabstractmethod__ = True def __init__(self, callable): callable.__isabstractmethod__ = True super().__init__(callable) class abstractproperty(property): """ A decorator indicating abstract properties. Requires that the metaclass is ABCMeta or derived from it. A class that has a metaclass derived from ABCMeta cannot be instantiated unless all of its abstract properties are overridden. The abstract properties can be called using any of the normal 'super' call mechanisms. Usage: class C(metaclass=ABCMeta): @abstractproperty def my_abstract_property(self): ... This defines a read-only property; you can also define a read-write abstract property using the 'long' form of property declaration: class C(metaclass=ABCMeta): def getx(self): ... def setx(self, value): ... x = abstractproperty(getx, setx) 'abstractproperty' is deprecated. Use 'property' with 'abstractmethod' instead. """ __isabstractmethod__ = True class ABCMeta(type): """Metaclass for defining Abstract Base Classes (ABCs). Use this metaclass to create an ABC. An ABC can be subclassed directly, and then acts as a mix-in class. You can also register unrelated concrete classes (even built-in classes) and unrelated ABCs as 'virtual subclasses' -- these and their descendants will be considered subclasses of the registering ABC by the built-in issubclass() function, but the registering ABC won't show up in their MRO (Method Resolution Order) nor will method implementations defined by the registering ABC be callable (not even via super()). """ # A global counter that is incremented each time a class is # registered as a virtual subclass of anything. It forces the # negative cache to be cleared before its next use. # Note: this counter is private. Use `abc.get_cache_token()` for # external code. _abc_invalidation_counter = 0 def __new__(mcls, name, bases, namespace, **kwargs): cls = super().__new__(mcls, name, bases, namespace, **kwargs) # Compute set of abstract method names abstracts = {name for name, value in namespace.items() if getattr(value, "__isabstractmethod__", False)} for base in bases: for name in getattr(base, "__abstractmethods__", set()): value = getattr(cls, name, None) if getattr(value, "__isabstractmethod__", False): abstracts.add(name) cls.__abstractmethods__ = frozenset(abstracts) # Set up inheritance registry cls._abc_registry = WeakSet() cls._abc_cache = WeakSet() cls._abc_negative_cache = WeakSet() cls._abc_negative_cache_version = ABCMeta._abc_invalidation_counter return cls def register(cls, subclass): """Register a virtual subclass of an ABC. Returns the subclass, to allow usage as a class decorator. """ if not isinstance(subclass, type): raise TypeError("Can only register classes") if issubclass(subclass, cls): return subclass # Already a subclass # Subtle: test for cycles *after* testing for "already a subclass"; # this means we allow X.register(X) and interpret it as a no-op. if issubclass(cls, subclass): # This would create a cycle, which is bad for the algorithm below raise RuntimeError("Refusing to create an inheritance cycle") cls._abc_registry.add(subclass) ABCMeta._abc_invalidation_counter += 1 # Invalidate negative cache return subclass def _dump_registry(cls, file=None): """Debug helper to print the ABC registry.""" print("Class: %s.%s" % (cls.__module__, cls.__qualname__), file=file) print("Inv.counter: %s" % ABCMeta._abc_invalidation_counter, file=file) for name in sorted(cls.__dict__): if name.startswith("_abc_"): value = getattr(cls, name) if isinstance(value, WeakSet): value = set(value) print("%s: %r" % (name, value), file=file) def __instancecheck__(cls, instance): """Override for isinstance(instance, cls).""" # Inline the cache checking subclass = instance.__class__ if subclass in cls._abc_cache: return True subtype = type(instance) if subtype is subclass: if (cls._abc_negative_cache_version == ABCMeta._abc_invalidation_counter and subclass in cls._abc_negative_cache): return False # Fall back to the subclass check. return cls.__subclasscheck__(subclass) return any(cls.__subclasscheck__(c) for c in {subclass, subtype}) def __subclasscheck__(cls, subclass): """Override for issubclass(subclass, cls).""" # Check cache if subclass in cls._abc_cache: return True # Check negative cache; may have to invalidate if cls._abc_negative_cache_version < ABCMeta._abc_invalidation_counter: # Invalidate the negative cache cls._abc_negative_cache = WeakSet() cls._abc_negative_cache_version = ABCMeta._abc_invalidation_counter elif subclass in cls._abc_negative_cache: return False # Check the subclass hook ok = cls.__subclasshook__(subclass) if ok is not NotImplemented: assert isinstance(ok, bool) if ok: cls._abc_cache.add(subclass) else: cls._abc_negative_cache.add(subclass) return ok # Check if it's a direct subclass if cls in getattr(subclass, '__mro__', ()): cls._abc_cache.add(subclass) return True # Check if it's a subclass of a registered class (recursive) for rcls in cls._abc_registry: if issubclass(subclass, rcls): cls._abc_cache.add(subclass) return True # Check if it's a subclass of a subclass (recursive) for scls in cls.__subclasses__(): if issubclass(subclass, scls): cls._abc_cache.add(subclass) return True # No dice; update negative cache cls._abc_negative_cache.add(subclass) return False class ABC(metaclass=ABCMeta): """Helper class that provides a standard way to create an ABC using inheritance. """ pass def get_cache_token(): """Returns the current ABC cache token. The token is an opaque object (supporting equality testing) identifying the current version of the ABC cache for virtual subclasses. The token changes with every call to ``register()`` on any ABC. """ return ABCMeta._abc_invalidation_counter lib64/python3.12/abc.py000064400000014612152343472100010415 0ustar00# Copyright 2007 Google, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. """Abstract Base Classes (ABCs) according to PEP 3119.""" def abstractmethod(funcobj): """A decorator indicating abstract methods. Requires that the metaclass is ABCMeta or derived from it. A class that has a metaclass derived from ABCMeta cannot be instantiated unless all of its abstract methods are overridden. The abstract methods can be called using any of the normal 'super' call mechanisms. abstractmethod() may be used to declare abstract methods for properties and descriptors. Usage: class C(metaclass=ABCMeta): @abstractmethod def my_abstract_method(self, arg1, arg2, argN): ... """ funcobj.__isabstractmethod__ = True return funcobj class abstractclassmethod(classmethod): """A decorator indicating abstract classmethods. Deprecated, use 'classmethod' with 'abstractmethod' instead: class C(ABC): @classmethod @abstractmethod def my_abstract_classmethod(cls, ...): ... """ __isabstractmethod__ = True def __init__(self, callable): callable.__isabstractmethod__ = True super().__init__(callable) class abstractstaticmethod(staticmethod): """A decorator indicating abstract staticmethods. Deprecated, use 'staticmethod' with 'abstractmethod' instead: class C(ABC): @staticmethod @abstractmethod def my_abstract_staticmethod(...): ... """ __isabstractmethod__ = True def __init__(self, callable): callable.__isabstractmethod__ = True super().__init__(callable) class abstractproperty(property): """A decorator indicating abstract properties. Deprecated, use 'property' with 'abstractmethod' instead: class C(ABC): @property @abstractmethod def my_abstract_property(self): ... """ __isabstractmethod__ = True try: from _abc import (get_cache_token, _abc_init, _abc_register, _abc_instancecheck, _abc_subclasscheck, _get_dump, _reset_registry, _reset_caches) except ImportError: from _py_abc import ABCMeta, get_cache_token ABCMeta.__module__ = 'abc' else: class ABCMeta(type): """Metaclass for defining Abstract Base Classes (ABCs). Use this metaclass to create an ABC. An ABC can be subclassed directly, and then acts as a mix-in class. You can also register unrelated concrete classes (even built-in classes) and unrelated ABCs as 'virtual subclasses' -- these and their descendants will be considered subclasses of the registering ABC by the built-in issubclass() function, but the registering ABC won't show up in their MRO (Method Resolution Order) nor will method implementations defined by the registering ABC be callable (not even via super()). """ def __new__(mcls, name, bases, namespace, /, **kwargs): cls = super().__new__(mcls, name, bases, namespace, **kwargs) _abc_init(cls) return cls def register(cls, subclass): """Register a virtual subclass of an ABC. Returns the subclass, to allow usage as a class decorator. """ return _abc_register(cls, subclass) def __instancecheck__(cls, instance): """Override for isinstance(instance, cls).""" return _abc_instancecheck(cls, instance) def __subclasscheck__(cls, subclass): """Override for issubclass(subclass, cls).""" return _abc_subclasscheck(cls, subclass) def _dump_registry(cls, file=None): """Debug helper to print the ABC registry.""" print(f"Class: {cls.__module__}.{cls.__qualname__}", file=file) print(f"Inv. counter: {get_cache_token()}", file=file) (_abc_registry, _abc_cache, _abc_negative_cache, _abc_negative_cache_version) = _get_dump(cls) print(f"_abc_registry: {_abc_registry!r}", file=file) print(f"_abc_cache: {_abc_cache!r}", file=file) print(f"_abc_negative_cache: {_abc_negative_cache!r}", file=file) print(f"_abc_negative_cache_version: {_abc_negative_cache_version!r}", file=file) def _abc_registry_clear(cls): """Clear the registry (for debugging or testing).""" _reset_registry(cls) def _abc_caches_clear(cls): """Clear the caches (for debugging or testing).""" _reset_caches(cls) def update_abstractmethods(cls): """Recalculate the set of abstract methods of an abstract class. If a class has had one of its abstract methods implemented after the class was created, the method will not be considered implemented until this function is called. Alternatively, if a new abstract method has been added to the class, it will only be considered an abstract method of the class after this function is called. This function should be called before any use is made of the class, usually in class decorators that add methods to the subject class. Returns cls, to allow usage as a class decorator. If cls is not an instance of ABCMeta, does nothing. """ if not hasattr(cls, '__abstractmethods__'): # We check for __abstractmethods__ here because cls might by a C # implementation or a python implementation (especially during # testing), and we want to handle both cases. return cls abstracts = set() # Check the existing abstract methods of the parents, keep only the ones # that are not implemented. for scls in cls.__bases__: for name in getattr(scls, '__abstractmethods__', ()): value = getattr(cls, name, None) if getattr(value, "__isabstractmethod__", False): abstracts.add(name) # Also add any other newly added abstract methods. for name, value in cls.__dict__.items(): if getattr(value, "__isabstractmethod__", False): abstracts.add(name) cls.__abstractmethods__ = frozenset(abstracts) return cls class ABC(metaclass=ABCMeta): """Helper class that provides a standard way to create an ABC using inheritance. """ __slots__ = () usr/lib64/python3.8/abc.py000064400000010611152343633360011155 0ustar00# Copyright 2007 Google, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. """Abstract Base Classes (ABCs) according to PEP 3119.""" def abstractmethod(funcobj): """A decorator indicating abstract methods. Requires that the metaclass is ABCMeta or derived from it. A class that has a metaclass derived from ABCMeta cannot be instantiated unless all of its abstract methods are overridden. The abstract methods can be called using any of the normal 'super' call mechanisms. abstractmethod() may be used to declare abstract methods for properties and descriptors. Usage: class C(metaclass=ABCMeta): @abstractmethod def my_abstract_method(self, ...): ... """ funcobj.__isabstractmethod__ = True return funcobj class abstractclassmethod(classmethod): """A decorator indicating abstract classmethods. Deprecated, use 'classmethod' with 'abstractmethod' instead. """ __isabstractmethod__ = True def __init__(self, callable): callable.__isabstractmethod__ = True super().__init__(callable) class abstractstaticmethod(staticmethod): """A decorator indicating abstract staticmethods. Deprecated, use 'staticmethod' with 'abstractmethod' instead. """ __isabstractmethod__ = True def __init__(self, callable): callable.__isabstractmethod__ = True super().__init__(callable) class abstractproperty(property): """A decorator indicating abstract properties. Deprecated, use 'property' with 'abstractmethod' instead. """ __isabstractmethod__ = True try: from _abc import (get_cache_token, _abc_init, _abc_register, _abc_instancecheck, _abc_subclasscheck, _get_dump, _reset_registry, _reset_caches) except ImportError: from _py_abc import ABCMeta, get_cache_token ABCMeta.__module__ = 'abc' else: class ABCMeta(type): """Metaclass for defining Abstract Base Classes (ABCs). Use this metaclass to create an ABC. An ABC can be subclassed directly, and then acts as a mix-in class. You can also register unrelated concrete classes (even built-in classes) and unrelated ABCs as 'virtual subclasses' -- these and their descendants will be considered subclasses of the registering ABC by the built-in issubclass() function, but the registering ABC won't show up in their MRO (Method Resolution Order) nor will method implementations defined by the registering ABC be callable (not even via super()). """ def __new__(mcls, name, bases, namespace, **kwargs): cls = super().__new__(mcls, name, bases, namespace, **kwargs) _abc_init(cls) return cls def register(cls, subclass): """Register a virtual subclass of an ABC. Returns the subclass, to allow usage as a class decorator. """ return _abc_register(cls, subclass) def __instancecheck__(cls, instance): """Override for isinstance(instance, cls).""" return _abc_instancecheck(cls, instance) def __subclasscheck__(cls, subclass): """Override for issubclass(subclass, cls).""" return _abc_subclasscheck(cls, subclass) def _dump_registry(cls, file=None): """Debug helper to print the ABC registry.""" print(f"Class: {cls.__module__}.{cls.__qualname__}", file=file) print(f"Inv. counter: {get_cache_token()}", file=file) (_abc_registry, _abc_cache, _abc_negative_cache, _abc_negative_cache_version) = _get_dump(cls) print(f"_abc_registry: {_abc_registry!r}", file=file) print(f"_abc_cache: {_abc_cache!r}", file=file) print(f"_abc_negative_cache: {_abc_negative_cache!r}", file=file) print(f"_abc_negative_cache_version: {_abc_negative_cache_version!r}", file=file) def _abc_registry_clear(cls): """Clear the registry (for debugging or testing).""" _reset_registry(cls) def _abc_caches_clear(cls): """Clear the caches (for debugging or testing).""" _reset_caches(cls) class ABC(metaclass=ABCMeta): """Helper class that provides a standard way to create an ABC using inheritance. """ __slots__ = () lib64/python3.12/collections/abc.py000064400000000167152344565670012753 0ustar00from _collections_abc import * from _collections_abc import __all__ from _collections_abc import _CallableGenericAlias usr/lib64/python3.8/importlib/abc.py000064400000031111152345603530013152 0ustar00"""Abstract base classes related to import.""" from . import _bootstrap from . import _bootstrap_external from . import machinery try: import _frozen_importlib except ImportError as exc: if exc.name != '_frozen_importlib': raise _frozen_importlib = None try: import _frozen_importlib_external except ImportError as exc: _frozen_importlib_external = _bootstrap_external import abc import warnings def _register(abstract_cls, *classes): for cls in classes: abstract_cls.register(cls) if _frozen_importlib is not None: try: frozen_cls = getattr(_frozen_importlib, cls.__name__) except AttributeError: frozen_cls = getattr(_frozen_importlib_external, cls.__name__) abstract_cls.register(frozen_cls) class Finder(metaclass=abc.ABCMeta): """Legacy abstract base class for import finders. It may be subclassed for compatibility with legacy third party reimplementations of the import system. Otherwise, finder implementations should derive from the more specific MetaPathFinder or PathEntryFinder ABCs. Deprecated since Python 3.3 """ @abc.abstractmethod def find_module(self, fullname, path=None): """An abstract method that should find a module. The fullname is a str and the optional path is a str or None. Returns a Loader object or None. """ class MetaPathFinder(Finder): """Abstract base class for import finders on sys.meta_path.""" # We don't define find_spec() here since that would break # hasattr checks we do to support backward compatibility. def find_module(self, fullname, path): """Return a loader for the module. If no module is found, return None. The fullname is a str and the path is a list of strings or None. This method is deprecated since Python 3.4 in favor of finder.find_spec(). If find_spec() exists then backwards-compatible functionality is provided for this method. """ warnings.warn("MetaPathFinder.find_module() is deprecated since Python " "3.4 in favor of MetaPathFinder.find_spec() " "(available since 3.4)", DeprecationWarning, stacklevel=2) if not hasattr(self, 'find_spec'): return None found = self.find_spec(fullname, path) return found.loader if found is not None else None def invalidate_caches(self): """An optional method for clearing the finder's cache, if any. This method is used by importlib.invalidate_caches(). """ _register(MetaPathFinder, machinery.BuiltinImporter, machinery.FrozenImporter, machinery.PathFinder, machinery.WindowsRegistryFinder) class PathEntryFinder(Finder): """Abstract base class for path entry finders used by PathFinder.""" # We don't define find_spec() here since that would break # hasattr checks we do to support backward compatibility. def find_loader(self, fullname): """Return (loader, namespace portion) for the path entry. The fullname is a str. The namespace portion is a sequence of path entries contributing to part of a namespace package. The sequence may be empty. If loader is not None, the portion will be ignored. The portion will be discarded if another path entry finder locates the module as a normal module or package. This method is deprecated since Python 3.4 in favor of finder.find_spec(). If find_spec() is provided than backwards-compatible functionality is provided. """ warnings.warn("PathEntryFinder.find_loader() is deprecated since Python " "3.4 in favor of PathEntryFinder.find_spec() " "(available since 3.4)", DeprecationWarning, stacklevel=2) if not hasattr(self, 'find_spec'): return None, [] found = self.find_spec(fullname) if found is not None: if not found.submodule_search_locations: portions = [] else: portions = found.submodule_search_locations return found.loader, portions else: return None, [] find_module = _bootstrap_external._find_module_shim def invalidate_caches(self): """An optional method for clearing the finder's cache, if any. This method is used by PathFinder.invalidate_caches(). """ _register(PathEntryFinder, machinery.FileFinder) class Loader(metaclass=abc.ABCMeta): """Abstract base class for import loaders.""" def create_module(self, spec): """Return a module to initialize and into which to load. This method should raise ImportError if anything prevents it from creating a new module. It may return None to indicate that the spec should create the new module. """ # By default, defer to default semantics for the new module. return None # We don't define exec_module() here since that would break # hasattr checks we do to support backward compatibility. def load_module(self, fullname): """Return the loaded module. The module must be added to sys.modules and have import-related attributes set properly. The fullname is a str. ImportError is raised on failure. This method is deprecated in favor of loader.exec_module(). If exec_module() exists then it is used to provide a backwards-compatible functionality for this method. """ if not hasattr(self, 'exec_module'): raise ImportError return _bootstrap._load_module_shim(self, fullname) def module_repr(self, module): """Return a module's repr. Used by the module type when the method does not raise NotImplementedError. This method is deprecated. """ # The exception will cause ModuleType.__repr__ to ignore this method. raise NotImplementedError class ResourceLoader(Loader): """Abstract base class for loaders which can return data from their back-end storage. This ABC represents one of the optional protocols specified by PEP 302. """ @abc.abstractmethod def get_data(self, path): """Abstract method which when implemented should return the bytes for the specified path. The path must be a str.""" raise OSError class InspectLoader(Loader): """Abstract base class for loaders which support inspection about the modules they can load. This ABC represents one of the optional protocols specified by PEP 302. """ def is_package(self, fullname): """Optional method which when implemented should return whether the module is a package. The fullname is a str. Returns a bool. Raises ImportError if the module cannot be found. """ raise ImportError def get_code(self, fullname): """Method which returns the code object for the module. The fullname is a str. Returns a types.CodeType if possible, else returns None if a code object does not make sense (e.g. built-in module). Raises ImportError if the module cannot be found. """ source = self.get_source(fullname) if source is None: return None return self.source_to_code(source) @abc.abstractmethod def get_source(self, fullname): """Abstract method which should return the source code for the module. The fullname is a str. Returns a str. Raises ImportError if the module cannot be found. """ raise ImportError @staticmethod def source_to_code(data, path=''): """Compile 'data' into a code object. The 'data' argument can be anything that compile() can handle. The'path' argument should be where the data was retrieved (when applicable).""" return compile(data, path, 'exec', dont_inherit=True) exec_module = _bootstrap_external._LoaderBasics.exec_module load_module = _bootstrap_external._LoaderBasics.load_module _register(InspectLoader, machinery.BuiltinImporter, machinery.FrozenImporter) class ExecutionLoader(InspectLoader): """Abstract base class for loaders that wish to support the execution of modules as scripts. This ABC represents one of the optional protocols specified in PEP 302. """ @abc.abstractmethod def get_filename(self, fullname): """Abstract method which should return the value that __file__ is to be set to. Raises ImportError if the module cannot be found. """ raise ImportError def get_code(self, fullname): """Method to return the code object for fullname. Should return None if not applicable (e.g. built-in module). Raise ImportError if the module cannot be found. """ source = self.get_source(fullname) if source is None: return None try: path = self.get_filename(fullname) except ImportError: return self.source_to_code(source) else: return self.source_to_code(source, path) _register(ExecutionLoader, machinery.ExtensionFileLoader) class FileLoader(_bootstrap_external.FileLoader, ResourceLoader, ExecutionLoader): """Abstract base class partially implementing the ResourceLoader and ExecutionLoader ABCs.""" _register(FileLoader, machinery.SourceFileLoader, machinery.SourcelessFileLoader) class SourceLoader(_bootstrap_external.SourceLoader, ResourceLoader, ExecutionLoader): """Abstract base class for loading source code (and optionally any corresponding bytecode). To support loading from source code, the abstractmethods inherited from ResourceLoader and ExecutionLoader need to be implemented. To also support loading from bytecode, the optional methods specified directly by this ABC is required. Inherited abstractmethods not implemented in this ABC: * ResourceLoader.get_data * ExecutionLoader.get_filename """ def path_mtime(self, path): """Return the (int) modification time for the path (str).""" if self.path_stats.__func__ is SourceLoader.path_stats: raise OSError return int(self.path_stats(path)['mtime']) def path_stats(self, path): """Return a metadata dict for the source pointed to by the path (str). Possible keys: - 'mtime' (mandatory) is the numeric timestamp of last source code modification; - 'size' (optional) is the size in bytes of the source code. """ if self.path_mtime.__func__ is SourceLoader.path_mtime: raise OSError return {'mtime': self.path_mtime(path)} def set_data(self, path, data): """Write the bytes to the path (if possible). Accepts a str path and data as bytes. Any needed intermediary directories are to be created. If for some reason the file cannot be written because of permissions, fail silently. """ _register(SourceLoader, machinery.SourceFileLoader) class ResourceReader(metaclass=abc.ABCMeta): """Abstract base class to provide resource-reading support. Loaders that support resource reading are expected to implement the ``get_resource_reader(fullname)`` method and have it either return None or an object compatible with this ABC. """ @abc.abstractmethod def open_resource(self, resource): """Return an opened, file-like object for binary reading. The 'resource' argument is expected to represent only a file name and thus not contain any subdirectory components. If the resource cannot be found, FileNotFoundError is raised. """ raise FileNotFoundError @abc.abstractmethod def resource_path(self, resource): """Return the file system path to the specified resource. The 'resource' argument is expected to represent only a file name and thus not contain any subdirectory components. If the resource does not exist on the file system, raise FileNotFoundError. """ raise FileNotFoundError @abc.abstractmethod def is_resource(self, name): """Return True if the named 'name' is consider a resource.""" raise FileNotFoundError @abc.abstractmethod def contents(self): """Return an iterable of strings over the contents of the package.""" return [] _register(ResourceReader, machinery.SourceFileLoader) lib64/python3.12/importlib/abc.py000064400000016674152346114720012434 0ustar00"""Abstract base classes related to import.""" from . import _bootstrap_external from . import machinery try: import _frozen_importlib except ImportError as exc: if exc.name != '_frozen_importlib': raise _frozen_importlib = None try: import _frozen_importlib_external except ImportError: _frozen_importlib_external = _bootstrap_external from ._abc import Loader import abc import warnings from .resources import abc as _resources_abc __all__ = [ 'Loader', 'MetaPathFinder', 'PathEntryFinder', 'ResourceLoader', 'InspectLoader', 'ExecutionLoader', 'FileLoader', 'SourceLoader', ] def __getattr__(name): """ For backwards compatibility, continue to make names from _resources_abc available through this module. #93963 """ if name in _resources_abc.__all__: obj = getattr(_resources_abc, name) warnings._deprecated(f"{__name__}.{name}", remove=(3, 14)) globals()[name] = obj return obj raise AttributeError(f'module {__name__!r} has no attribute {name!r}') def _register(abstract_cls, *classes): for cls in classes: abstract_cls.register(cls) if _frozen_importlib is not None: try: frozen_cls = getattr(_frozen_importlib, cls.__name__) except AttributeError: frozen_cls = getattr(_frozen_importlib_external, cls.__name__) abstract_cls.register(frozen_cls) class MetaPathFinder(metaclass=abc.ABCMeta): """Abstract base class for import finders on sys.meta_path.""" # We don't define find_spec() here since that would break # hasattr checks we do to support backward compatibility. def invalidate_caches(self): """An optional method for clearing the finder's cache, if any. This method is used by importlib.invalidate_caches(). """ _register(MetaPathFinder, machinery.BuiltinImporter, machinery.FrozenImporter, machinery.PathFinder, machinery.WindowsRegistryFinder) class PathEntryFinder(metaclass=abc.ABCMeta): """Abstract base class for path entry finders used by PathFinder.""" def invalidate_caches(self): """An optional method for clearing the finder's cache, if any. This method is used by PathFinder.invalidate_caches(). """ _register(PathEntryFinder, machinery.FileFinder) class ResourceLoader(Loader): """Abstract base class for loaders which can return data from their back-end storage. This ABC represents one of the optional protocols specified by PEP 302. """ @abc.abstractmethod def get_data(self, path): """Abstract method which when implemented should return the bytes for the specified path. The path must be a str.""" raise OSError class InspectLoader(Loader): """Abstract base class for loaders which support inspection about the modules they can load. This ABC represents one of the optional protocols specified by PEP 302. """ def is_package(self, fullname): """Optional method which when implemented should return whether the module is a package. The fullname is a str. Returns a bool. Raises ImportError if the module cannot be found. """ raise ImportError def get_code(self, fullname): """Method which returns the code object for the module. The fullname is a str. Returns a types.CodeType if possible, else returns None if a code object does not make sense (e.g. built-in module). Raises ImportError if the module cannot be found. """ source = self.get_source(fullname) if source is None: return None return self.source_to_code(source) @abc.abstractmethod def get_source(self, fullname): """Abstract method which should return the source code for the module. The fullname is a str. Returns a str. Raises ImportError if the module cannot be found. """ raise ImportError @staticmethod def source_to_code(data, path=''): """Compile 'data' into a code object. The 'data' argument can be anything that compile() can handle. The'path' argument should be where the data was retrieved (when applicable).""" return compile(data, path, 'exec', dont_inherit=True) exec_module = _bootstrap_external._LoaderBasics.exec_module load_module = _bootstrap_external._LoaderBasics.load_module _register(InspectLoader, machinery.BuiltinImporter, machinery.FrozenImporter, machinery.NamespaceLoader) class ExecutionLoader(InspectLoader): """Abstract base class for loaders that wish to support the execution of modules as scripts. This ABC represents one of the optional protocols specified in PEP 302. """ @abc.abstractmethod def get_filename(self, fullname): """Abstract method which should return the value that __file__ is to be set to. Raises ImportError if the module cannot be found. """ raise ImportError def get_code(self, fullname): """Method to return the code object for fullname. Should return None if not applicable (e.g. built-in module). Raise ImportError if the module cannot be found. """ source = self.get_source(fullname) if source is None: return None try: path = self.get_filename(fullname) except ImportError: return self.source_to_code(source) else: return self.source_to_code(source, path) _register(ExecutionLoader, machinery.ExtensionFileLoader) class FileLoader(_bootstrap_external.FileLoader, ResourceLoader, ExecutionLoader): """Abstract base class partially implementing the ResourceLoader and ExecutionLoader ABCs.""" _register(FileLoader, machinery.SourceFileLoader, machinery.SourcelessFileLoader) class SourceLoader(_bootstrap_external.SourceLoader, ResourceLoader, ExecutionLoader): """Abstract base class for loading source code (and optionally any corresponding bytecode). To support loading from source code, the abstractmethods inherited from ResourceLoader and ExecutionLoader need to be implemented. To also support loading from bytecode, the optional methods specified directly by this ABC is required. Inherited abstractmethods not implemented in this ABC: * ResourceLoader.get_data * ExecutionLoader.get_filename """ def path_mtime(self, path): """Return the (int) modification time for the path (str).""" if self.path_stats.__func__ is SourceLoader.path_stats: raise OSError return int(self.path_stats(path)['mtime']) def path_stats(self, path): """Return a metadata dict for the source pointed to by the path (str). Possible keys: - 'mtime' (mandatory) is the numeric timestamp of last source code modification; - 'size' (optional) is the size in bytes of the source code. """ if self.path_mtime.__func__ is SourceLoader.path_mtime: raise OSError return {'mtime': self.path_mtime(path)} def set_data(self, path, data): """Write the bytes to the path (if possible). Accepts a str path and data as bytes. Any needed intermediary directories are to be created. If for some reason the file cannot be written because of permissions, fail silently. """ _register(SourceLoader, machinery.SourceFileLoader) usr/lib64/python3.8/collections/abc.py000064400000000104152346172000013457 0ustar00from _collections_abc import * from _collections_abc import __all__ usr/lib64/python3.12/abc.py000064400000014612152347153370011237 0ustar00# Copyright 2007 Google, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. """Abstract Base Classes (ABCs) according to PEP 3119.""" def abstractmethod(funcobj): """A decorator indicating abstract methods. Requires that the metaclass is ABCMeta or derived from it. A class that has a metaclass derived from ABCMeta cannot be instantiated unless all of its abstract methods are overridden. The abstract methods can be called using any of the normal 'super' call mechanisms. abstractmethod() may be used to declare abstract methods for properties and descriptors. Usage: class C(metaclass=ABCMeta): @abstractmethod def my_abstract_method(self, arg1, arg2, argN): ... """ funcobj.__isabstractmethod__ = True return funcobj class abstractclassmethod(classmethod): """A decorator indicating abstract classmethods. Deprecated, use 'classmethod' with 'abstractmethod' instead: class C(ABC): @classmethod @abstractmethod def my_abstract_classmethod(cls, ...): ... """ __isabstractmethod__ = True def __init__(self, callable): callable.__isabstractmethod__ = True super().__init__(callable) class abstractstaticmethod(staticmethod): """A decorator indicating abstract staticmethods. Deprecated, use 'staticmethod' with 'abstractmethod' instead: class C(ABC): @staticmethod @abstractmethod def my_abstract_staticmethod(...): ... """ __isabstractmethod__ = True def __init__(self, callable): callable.__isabstractmethod__ = True super().__init__(callable) class abstractproperty(property): """A decorator indicating abstract properties. Deprecated, use 'property' with 'abstractmethod' instead: class C(ABC): @property @abstractmethod def my_abstract_property(self): ... """ __isabstractmethod__ = True try: from _abc import (get_cache_token, _abc_init, _abc_register, _abc_instancecheck, _abc_subclasscheck, _get_dump, _reset_registry, _reset_caches) except ImportError: from _py_abc import ABCMeta, get_cache_token ABCMeta.__module__ = 'abc' else: class ABCMeta(type): """Metaclass for defining Abstract Base Classes (ABCs). Use this metaclass to create an ABC. An ABC can be subclassed directly, and then acts as a mix-in class. You can also register unrelated concrete classes (even built-in classes) and unrelated ABCs as 'virtual subclasses' -- these and their descendants will be considered subclasses of the registering ABC by the built-in issubclass() function, but the registering ABC won't show up in their MRO (Method Resolution Order) nor will method implementations defined by the registering ABC be callable (not even via super()). """ def __new__(mcls, name, bases, namespace, /, **kwargs): cls = super().__new__(mcls, name, bases, namespace, **kwargs) _abc_init(cls) return cls def register(cls, subclass): """Register a virtual subclass of an ABC. Returns the subclass, to allow usage as a class decorator. """ return _abc_register(cls, subclass) def __instancecheck__(cls, instance): """Override for isinstance(instance, cls).""" return _abc_instancecheck(cls, instance) def __subclasscheck__(cls, subclass): """Override for issubclass(subclass, cls).""" return _abc_subclasscheck(cls, subclass) def _dump_registry(cls, file=None): """Debug helper to print the ABC registry.""" print(f"Class: {cls.__module__}.{cls.__qualname__}", file=file) print(f"Inv. counter: {get_cache_token()}", file=file) (_abc_registry, _abc_cache, _abc_negative_cache, _abc_negative_cache_version) = _get_dump(cls) print(f"_abc_registry: {_abc_registry!r}", file=file) print(f"_abc_cache: {_abc_cache!r}", file=file) print(f"_abc_negative_cache: {_abc_negative_cache!r}", file=file) print(f"_abc_negative_cache_version: {_abc_negative_cache_version!r}", file=file) def _abc_registry_clear(cls): """Clear the registry (for debugging or testing).""" _reset_registry(cls) def _abc_caches_clear(cls): """Clear the caches (for debugging or testing).""" _reset_caches(cls) def update_abstractmethods(cls): """Recalculate the set of abstract methods of an abstract class. If a class has had one of its abstract methods implemented after the class was created, the method will not be considered implemented until this function is called. Alternatively, if a new abstract method has been added to the class, it will only be considered an abstract method of the class after this function is called. This function should be called before any use is made of the class, usually in class decorators that add methods to the subject class. Returns cls, to allow usage as a class decorator. If cls is not an instance of ABCMeta, does nothing. """ if not hasattr(cls, '__abstractmethods__'): # We check for __abstractmethods__ here because cls might by a C # implementation or a python implementation (especially during # testing), and we want to handle both cases. return cls abstracts = set() # Check the existing abstract methods of the parents, keep only the ones # that are not implemented. for scls in cls.__bases__: for name in getattr(scls, '__abstractmethods__', ()): value = getattr(cls, name, None) if getattr(value, "__isabstractmethod__", False): abstracts.add(name) # Also add any other newly added abstract methods. for name, value in cls.__dict__.items(): if getattr(value, "__isabstractmethod__", False): abstracts.add(name) cls.__abstractmethods__ = frozenset(abstracts) return cls class ABC(metaclass=ABCMeta): """Helper class that provides a standard way to create an ABC using inheritance. """ __slots__ = () lib64/python3.8/collections/abc.py000064400000000104152347233270012656 0ustar00from _collections_abc import * from _collections_abc import __all__ usr/lib64/python3.6/collections/abc.py000064400000000104152347727600013472 0ustar00from _collections_abc import * from _collections_abc import __all__ lib64/python3.8/importlib/abc.py000064400000031111152350307100012327 0ustar00"""Abstract base classes related to import.""" from . import _bootstrap from . import _bootstrap_external from . import machinery try: import _frozen_importlib except ImportError as exc: if exc.name != '_frozen_importlib': raise _frozen_importlib = None try: import _frozen_importlib_external except ImportError as exc: _frozen_importlib_external = _bootstrap_external import abc import warnings def _register(abstract_cls, *classes): for cls in classes: abstract_cls.register(cls) if _frozen_importlib is not None: try: frozen_cls = getattr(_frozen_importlib, cls.__name__) except AttributeError: frozen_cls = getattr(_frozen_importlib_external, cls.__name__) abstract_cls.register(frozen_cls) class Finder(metaclass=abc.ABCMeta): """Legacy abstract base class for import finders. It may be subclassed for compatibility with legacy third party reimplementations of the import system. Otherwise, finder implementations should derive from the more specific MetaPathFinder or PathEntryFinder ABCs. Deprecated since Python 3.3 """ @abc.abstractmethod def find_module(self, fullname, path=None): """An abstract method that should find a module. The fullname is a str and the optional path is a str or None. Returns a Loader object or None. """ class MetaPathFinder(Finder): """Abstract base class for import finders on sys.meta_path.""" # We don't define find_spec() here since that would break # hasattr checks we do to support backward compatibility. def find_module(self, fullname, path): """Return a loader for the module. If no module is found, return None. The fullname is a str and the path is a list of strings or None. This method is deprecated since Python 3.4 in favor of finder.find_spec(). If find_spec() exists then backwards-compatible functionality is provided for this method. """ warnings.warn("MetaPathFinder.find_module() is deprecated since Python " "3.4 in favor of MetaPathFinder.find_spec() " "(available since 3.4)", DeprecationWarning, stacklevel=2) if not hasattr(self, 'find_spec'): return None found = self.find_spec(fullname, path) return found.loader if found is not None else None def invalidate_caches(self): """An optional method for clearing the finder's cache, if any. This method is used by importlib.invalidate_caches(). """ _register(MetaPathFinder, machinery.BuiltinImporter, machinery.FrozenImporter, machinery.PathFinder, machinery.WindowsRegistryFinder) class PathEntryFinder(Finder): """Abstract base class for path entry finders used by PathFinder.""" # We don't define find_spec() here since that would break # hasattr checks we do to support backward compatibility. def find_loader(self, fullname): """Return (loader, namespace portion) for the path entry. The fullname is a str. The namespace portion is a sequence of path entries contributing to part of a namespace package. The sequence may be empty. If loader is not None, the portion will be ignored. The portion will be discarded if another path entry finder locates the module as a normal module or package. This method is deprecated since Python 3.4 in favor of finder.find_spec(). If find_spec() is provided than backwards-compatible functionality is provided. """ warnings.warn("PathEntryFinder.find_loader() is deprecated since Python " "3.4 in favor of PathEntryFinder.find_spec() " "(available since 3.4)", DeprecationWarning, stacklevel=2) if not hasattr(self, 'find_spec'): return None, [] found = self.find_spec(fullname) if found is not None: if not found.submodule_search_locations: portions = [] else: portions = found.submodule_search_locations return found.loader, portions else: return None, [] find_module = _bootstrap_external._find_module_shim def invalidate_caches(self): """An optional method for clearing the finder's cache, if any. This method is used by PathFinder.invalidate_caches(). """ _register(PathEntryFinder, machinery.FileFinder) class Loader(metaclass=abc.ABCMeta): """Abstract base class for import loaders.""" def create_module(self, spec): """Return a module to initialize and into which to load. This method should raise ImportError if anything prevents it from creating a new module. It may return None to indicate that the spec should create the new module. """ # By default, defer to default semantics for the new module. return None # We don't define exec_module() here since that would break # hasattr checks we do to support backward compatibility. def load_module(self, fullname): """Return the loaded module. The module must be added to sys.modules and have import-related attributes set properly. The fullname is a str. ImportError is raised on failure. This method is deprecated in favor of loader.exec_module(). If exec_module() exists then it is used to provide a backwards-compatible functionality for this method. """ if not hasattr(self, 'exec_module'): raise ImportError return _bootstrap._load_module_shim(self, fullname) def module_repr(self, module): """Return a module's repr. Used by the module type when the method does not raise NotImplementedError. This method is deprecated. """ # The exception will cause ModuleType.__repr__ to ignore this method. raise NotImplementedError class ResourceLoader(Loader): """Abstract base class for loaders which can return data from their back-end storage. This ABC represents one of the optional protocols specified by PEP 302. """ @abc.abstractmethod def get_data(self, path): """Abstract method which when implemented should return the bytes for the specified path. The path must be a str.""" raise OSError class InspectLoader(Loader): """Abstract base class for loaders which support inspection about the modules they can load. This ABC represents one of the optional protocols specified by PEP 302. """ def is_package(self, fullname): """Optional method which when implemented should return whether the module is a package. The fullname is a str. Returns a bool. Raises ImportError if the module cannot be found. """ raise ImportError def get_code(self, fullname): """Method which returns the code object for the module. The fullname is a str. Returns a types.CodeType if possible, else returns None if a code object does not make sense (e.g. built-in module). Raises ImportError if the module cannot be found. """ source = self.get_source(fullname) if source is None: return None return self.source_to_code(source) @abc.abstractmethod def get_source(self, fullname): """Abstract method which should return the source code for the module. The fullname is a str. Returns a str. Raises ImportError if the module cannot be found. """ raise ImportError @staticmethod def source_to_code(data, path=''): """Compile 'data' into a code object. The 'data' argument can be anything that compile() can handle. The'path' argument should be where the data was retrieved (when applicable).""" return compile(data, path, 'exec', dont_inherit=True) exec_module = _bootstrap_external._LoaderBasics.exec_module load_module = _bootstrap_external._LoaderBasics.load_module _register(InspectLoader, machinery.BuiltinImporter, machinery.FrozenImporter) class ExecutionLoader(InspectLoader): """Abstract base class for loaders that wish to support the execution of modules as scripts. This ABC represents one of the optional protocols specified in PEP 302. """ @abc.abstractmethod def get_filename(self, fullname): """Abstract method which should return the value that __file__ is to be set to. Raises ImportError if the module cannot be found. """ raise ImportError def get_code(self, fullname): """Method to return the code object for fullname. Should return None if not applicable (e.g. built-in module). Raise ImportError if the module cannot be found. """ source = self.get_source(fullname) if source is None: return None try: path = self.get_filename(fullname) except ImportError: return self.source_to_code(source) else: return self.source_to_code(source, path) _register(ExecutionLoader, machinery.ExtensionFileLoader) class FileLoader(_bootstrap_external.FileLoader, ResourceLoader, ExecutionLoader): """Abstract base class partially implementing the ResourceLoader and ExecutionLoader ABCs.""" _register(FileLoader, machinery.SourceFileLoader, machinery.SourcelessFileLoader) class SourceLoader(_bootstrap_external.SourceLoader, ResourceLoader, ExecutionLoader): """Abstract base class for loading source code (and optionally any corresponding bytecode). To support loading from source code, the abstractmethods inherited from ResourceLoader and ExecutionLoader need to be implemented. To also support loading from bytecode, the optional methods specified directly by this ABC is required. Inherited abstractmethods not implemented in this ABC: * ResourceLoader.get_data * ExecutionLoader.get_filename """ def path_mtime(self, path): """Return the (int) modification time for the path (str).""" if self.path_stats.__func__ is SourceLoader.path_stats: raise OSError return int(self.path_stats(path)['mtime']) def path_stats(self, path): """Return a metadata dict for the source pointed to by the path (str). Possible keys: - 'mtime' (mandatory) is the numeric timestamp of last source code modification; - 'size' (optional) is the size in bytes of the source code. """ if self.path_mtime.__func__ is SourceLoader.path_mtime: raise OSError return {'mtime': self.path_mtime(path)} def set_data(self, path, data): """Write the bytes to the path (if possible). Accepts a str path and data as bytes. Any needed intermediary directories are to be created. If for some reason the file cannot be written because of permissions, fail silently. """ _register(SourceLoader, machinery.SourceFileLoader) class ResourceReader(metaclass=abc.ABCMeta): """Abstract base class to provide resource-reading support. Loaders that support resource reading are expected to implement the ``get_resource_reader(fullname)`` method and have it either return None or an object compatible with this ABC. """ @abc.abstractmethod def open_resource(self, resource): """Return an opened, file-like object for binary reading. The 'resource' argument is expected to represent only a file name and thus not contain any subdirectory components. If the resource cannot be found, FileNotFoundError is raised. """ raise FileNotFoundError @abc.abstractmethod def resource_path(self, resource): """Return the file system path to the specified resource. The 'resource' argument is expected to represent only a file name and thus not contain any subdirectory components. If the resource does not exist on the file system, raise FileNotFoundError. """ raise FileNotFoundError @abc.abstractmethod def is_resource(self, name): """Return True if the named 'name' is consider a resource.""" raise FileNotFoundError @abc.abstractmethod def contents(self): """Return an iterable of strings over the contents of the package.""" return [] _register(ResourceReader, machinery.SourceFileLoader) lib64/python3.6/importlib/abc.py000064400000025036152350316650012350 0ustar00"""Abstract base classes related to import.""" from . import _bootstrap from . import _bootstrap_external from . import machinery try: import _frozen_importlib except ImportError as exc: if exc.name != '_frozen_importlib': raise _frozen_importlib = None try: import _frozen_importlib_external except ImportError as exc: _frozen_importlib_external = _bootstrap_external import abc def _register(abstract_cls, *classes): for cls in classes: abstract_cls.register(cls) if _frozen_importlib is not None: try: frozen_cls = getattr(_frozen_importlib, cls.__name__) except AttributeError: frozen_cls = getattr(_frozen_importlib_external, cls.__name__) abstract_cls.register(frozen_cls) class Finder(metaclass=abc.ABCMeta): """Legacy abstract base class for import finders. It may be subclassed for compatibility with legacy third party reimplementations of the import system. Otherwise, finder implementations should derive from the more specific MetaPathFinder or PathEntryFinder ABCs. """ @abc.abstractmethod def find_module(self, fullname, path=None): """An abstract method that should find a module. The fullname is a str and the optional path is a str or None. Returns a Loader object or None. """ class MetaPathFinder(Finder): """Abstract base class for import finders on sys.meta_path.""" # We don't define find_spec() here since that would break # hasattr checks we do to support backward compatibility. def find_module(self, fullname, path): """Return a loader for the module. If no module is found, return None. The fullname is a str and the path is a list of strings or None. This method is deprecated in favor of finder.find_spec(). If find_spec() exists then backwards-compatible functionality is provided for this method. """ if not hasattr(self, 'find_spec'): return None found = self.find_spec(fullname, path) return found.loader if found is not None else None def invalidate_caches(self): """An optional method for clearing the finder's cache, if any. This method is used by importlib.invalidate_caches(). """ _register(MetaPathFinder, machinery.BuiltinImporter, machinery.FrozenImporter, machinery.PathFinder, machinery.WindowsRegistryFinder) class PathEntryFinder(Finder): """Abstract base class for path entry finders used by PathFinder.""" # We don't define find_spec() here since that would break # hasattr checks we do to support backward compatibility. def find_loader(self, fullname): """Return (loader, namespace portion) for the path entry. The fullname is a str. The namespace portion is a sequence of path entries contributing to part of a namespace package. The sequence may be empty. If loader is not None, the portion will be ignored. The portion will be discarded if another path entry finder locates the module as a normal module or package. This method is deprecated in favor of finder.find_spec(). If find_spec() is provided than backwards-compatible functionality is provided. """ if not hasattr(self, 'find_spec'): return None, [] found = self.find_spec(fullname) if found is not None: if not found.submodule_search_locations: portions = [] else: portions = found.submodule_search_locations return found.loader, portions else: return None, [] find_module = _bootstrap_external._find_module_shim def invalidate_caches(self): """An optional method for clearing the finder's cache, if any. This method is used by PathFinder.invalidate_caches(). """ _register(PathEntryFinder, machinery.FileFinder) class Loader(metaclass=abc.ABCMeta): """Abstract base class for import loaders.""" def create_module(self, spec): """Return a module to initialize and into which to load. This method should raise ImportError if anything prevents it from creating a new module. It may return None to indicate that the spec should create the new module. """ # By default, defer to default semantics for the new module. return None # We don't define exec_module() here since that would break # hasattr checks we do to support backward compatibility. def load_module(self, fullname): """Return the loaded module. The module must be added to sys.modules and have import-related attributes set properly. The fullname is a str. ImportError is raised on failure. This method is deprecated in favor of loader.exec_module(). If exec_module() exists then it is used to provide a backwards-compatible functionality for this method. """ if not hasattr(self, 'exec_module'): raise ImportError return _bootstrap._load_module_shim(self, fullname) def module_repr(self, module): """Return a module's repr. Used by the module type when the method does not raise NotImplementedError. This method is deprecated. """ # The exception will cause ModuleType.__repr__ to ignore this method. raise NotImplementedError class ResourceLoader(Loader): """Abstract base class for loaders which can return data from their back-end storage. This ABC represents one of the optional protocols specified by PEP 302. """ @abc.abstractmethod def get_data(self, path): """Abstract method which when implemented should return the bytes for the specified path. The path must be a str.""" raise IOError class InspectLoader(Loader): """Abstract base class for loaders which support inspection about the modules they can load. This ABC represents one of the optional protocols specified by PEP 302. """ def is_package(self, fullname): """Optional method which when implemented should return whether the module is a package. The fullname is a str. Returns a bool. Raises ImportError if the module cannot be found. """ raise ImportError def get_code(self, fullname): """Method which returns the code object for the module. The fullname is a str. Returns a types.CodeType if possible, else returns None if a code object does not make sense (e.g. built-in module). Raises ImportError if the module cannot be found. """ source = self.get_source(fullname) if source is None: return None return self.source_to_code(source) @abc.abstractmethod def get_source(self, fullname): """Abstract method which should return the source code for the module. The fullname is a str. Returns a str. Raises ImportError if the module cannot be found. """ raise ImportError @staticmethod def source_to_code(data, path=''): """Compile 'data' into a code object. The 'data' argument can be anything that compile() can handle. The'path' argument should be where the data was retrieved (when applicable).""" return compile(data, path, 'exec', dont_inherit=True) exec_module = _bootstrap_external._LoaderBasics.exec_module load_module = _bootstrap_external._LoaderBasics.load_module _register(InspectLoader, machinery.BuiltinImporter, machinery.FrozenImporter) class ExecutionLoader(InspectLoader): """Abstract base class for loaders that wish to support the execution of modules as scripts. This ABC represents one of the optional protocols specified in PEP 302. """ @abc.abstractmethod def get_filename(self, fullname): """Abstract method which should return the value that __file__ is to be set to. Raises ImportError if the module cannot be found. """ raise ImportError def get_code(self, fullname): """Method to return the code object for fullname. Should return None if not applicable (e.g. built-in module). Raise ImportError if the module cannot be found. """ source = self.get_source(fullname) if source is None: return None try: path = self.get_filename(fullname) except ImportError: return self.source_to_code(source) else: return self.source_to_code(source, path) _register(ExecutionLoader, machinery.ExtensionFileLoader) class FileLoader(_bootstrap_external.FileLoader, ResourceLoader, ExecutionLoader): """Abstract base class partially implementing the ResourceLoader and ExecutionLoader ABCs.""" _register(FileLoader, machinery.SourceFileLoader, machinery.SourcelessFileLoader) class SourceLoader(_bootstrap_external.SourceLoader, ResourceLoader, ExecutionLoader): """Abstract base class for loading source code (and optionally any corresponding bytecode). To support loading from source code, the abstractmethods inherited from ResourceLoader and ExecutionLoader need to be implemented. To also support loading from bytecode, the optional methods specified directly by this ABC is required. Inherited abstractmethods not implemented in this ABC: * ResourceLoader.get_data * ExecutionLoader.get_filename """ def path_mtime(self, path): """Return the (int) modification time for the path (str).""" if self.path_stats.__func__ is SourceLoader.path_stats: raise IOError return int(self.path_stats(path)['mtime']) def path_stats(self, path): """Return a metadata dict for the source pointed to by the path (str). Possible keys: - 'mtime' (mandatory) is the numeric timestamp of last source code modification; - 'size' (optional) is the size in bytes of the source code. """ if self.path_mtime.__func__ is SourceLoader.path_mtime: raise IOError return {'mtime': self.path_mtime(path)} def set_data(self, path, data): """Write the bytes to the path (if possible). Accepts a str path and data as bytes. Any needed intermediary directories are to be created. If for some reason the file cannot be written because of permissions, fail silently. """ _register(SourceLoader, machinery.SourceFileLoader)