00000068
  B   ˆl–Ü4ý( ©”u( 	•íÀà™S�ÿ�þYÎ,Ü¢#á�a	HçÂ„Ÿe¯Á_ŠI|¥�+Wé3ž¯ÁÀ 2†    # Copyright (C) 2006-2010 Canonical Ltd
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA

"""Classes to provide name-to-object registry-like support."""

from typing import (
    TypeVar,
    Generic,
    Optional,
    Any,
    cast,
    Union,
    Callable,
    Dict,
    List,
    Iterator,
    Tuple,
    Callable,
)

from .pyutils import get_named_object


T = TypeVar('T')


class _ObjectGetter(Generic[T]):
    """Maintain a reference to an object, and return the object on request.

    This is used by Registry to make plain objects function similarly
    to lazily imported objects.

    Objects can be any sort of python object (class, function, module,
    instance, etc)
    """

    __slots__ = ['_obj']

    _obj: T

    def __init__(self, obj):
        self._obj = obj

    def get_module(self) -> str:
        """Get the module the object was loaded from."""
        return self._obj.__module__

    def get_obj(self) -> T:
        """Get the object that was saved at creation time"""
        return self._obj


class _LazyObjectGetter(_ObjectGetter[T]):
    """Keep a record of a possible object.

    When requested, load and return it.
    """

    __slots__ = ['_module_name', '_member_name', '_imported']

    def __init__(self, module_name, member_name):
        self._module_name = module_name
        self._member_name = member_name
        self._imported = False
        super().__init__(None)

    def get_module(self):
        """Get the module the referenced object will be loaded from.
        """
        return self._module_name

    def get_obj(self) -> T:
        """Get the referenced object.

        Upon first request, the object will be imported. Future requests will
        return the imported object.
        """
        if not self._imported:
            self._obj = get_named_object(self._module_name, self._member_name)
            self._imported = True
        return super().get_obj()

    def __repr__(self):
        return "<{}.{} object at {:x}, module={!r} attribute={!r} imported={!r}>".format(
            self.__class__.__module__, self.__class__.__name__, id(self),
            self._module_name, self._member_name, self._imported)


K = TypeVar('K')
V = TypeVar('V')


class Registry(Generic[K, V]):
    """A class that registers objects to a name.

    There are many places that want to collect related objects and access them
    by a key. This class is designed to allow registering the mapping from key
    to object. It goes one step further, and allows registering a name to a
    hypothetical object which has not been imported yet. It also supports
    adding additional information at registration time so that decisions can be
    made without having to import the object (which may be expensive).

    The functions 'get', 'get_info', and 'get_help' also support a
    'default_key' (settable through my_registry.default_key = XXX, XXX must
    already be registered.) Calling my_registry.get() or my_registry.get(None),
    will return the entry for the default key.
    """

    def __init__(self) -> None:
        """Create a new Registry."""
        self._default_key = None
        self._dict: Dict[K, _ObjectGetter[V]] = {}
        self._aliases: Dict[K, K] = {}
        self._help_dict: Dict[K, Union[Callable[[Registry[K, V], Optional[K]], str], str]] = {}
        self._i