python类Type()的实例源码

test_is_type.py 文件源码 项目:typesentry 作者: h2oai 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def test_Type():
    from typing import Type, Any

    class A(object): pass

    class B(A): pass

    class C(B): pass

    class D(A): pass

    assert is_type(A, type)
    assert is_type(A, Type)
    assert is_type(A, Type[Any])
    assert is_type(A, Type[object])
    assert is_type(A, Type[A])
    assert is_type(B, Type[A])
    assert is_type(C, Type[A])
    assert is_type(C, Type[B])
    assert is_type(D, Type[A])
    assert not is_type(A, Type[B])
    assert not is_type(D, Type[B])
    assert not is_type("str", Type)
    assert not is_type(None, Type[A])
test_name_type.py 文件源码 项目:typesentry 作者: h2oai 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def test_typing():
    from typing import Any, List, Set, Dict, Type, Tuple
    assert name_type(Any) == "Any"
    assert name_type(List) == "List"
    assert name_type(List[Any]) == "List"
    assert name_type(List[str]) == "List[str]"
    assert name_type(List[int]) == "List[int]"
    assert name_type(Set) == "Set"
    assert name_type(Set[Any]) == "Set"
    assert name_type(Set[List]) == "Set[List]"
    assert name_type(Dict) == "Dict"
    assert name_type(Dict[Any, Any]) == "Dict"
    assert name_type(Dict[str, int]) == "Dict[str, int]"
    assert name_type(Type) == "Type"
    assert name_type(Type[int]) == "Type[int]"
    assert name_type(Type[MagicType]) == "Type[MagicType]"
    assert name_type(Tuple) == "Tuple"
    assert name_type(Tuple[int]) == "Tuple[int]"
    assert name_type(Tuple[int, str, List]) == "Tuple[int, str, List]"
    assert name_type(Tuple[int, Ellipsis]) == "Tuple[int, ...]"
    assert name_type(Tuple[str, Ellipsis]) == "Tuple[str, ...]"
cache.py 文件源码 项目:BAG_framework 作者: ucb-art 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def create_master_instance(self, gen_cls, lib_name, params, used_cell_names, **kwargs):
        # type: (Type[MasterType], str, Dict[str, Any], Set[str], **kwargs) -> MasterType
        """Create a new non-finalized master instance.

        This instance is used to determine if we created this instance before.

        Parameters
        ----------
        gen_cls : Type[MasterType]
            the generator Python class.
        lib_name : str
            generated instance library name.
        params : Dict[str, Any]
            instance parameters dictionary.
        used_cell_names : Set[str]
            a set of all used cell names.
        **kwargs
            optional arguments for the generator.

        Returns
        -------
        master : MasterType
            the non-finalized generated instance.
        """
        raise NotImplementedError('not implemented')
core.py 文件源码 项目:BAG_framework 作者: ucb-art 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def _import_class_from_str(class_str):
    # type: (str) -> Type
    """Given a Python class string, convert it to the Python class.

    Parameters
    ----------
    class_str : str
        a Python class string/

    Returns
    -------
    py_class : class
        a Python class.
    """
    sections = class_str.split('.')

    module_str = '.'.join(sections[:-1])
    class_str = sections[-1]
    modul = importlib.import_module(module_str)
    return getattr(modul, class_str)
state.py 文件源码 项目:curious 作者: SunDwarf 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
def make_user(self, user_data: dict, *,
                  user_klass: typing.Type[UserType] = User,
                  override_cache: bool = False) -> UserType:
        """
        Creates a new user and caches it.

        :param user_data: The user data to use to create.
        :param user_klass: The type of user to create.
        :param override_cache: Should the cache be overridden?
        :return: A new :class`~.User` (hopefully).
        """
        id = int(user_data.get("id", 0))
        if id in self._users and not override_cache:
            return self._users[id]

        user = user_klass(self.client, **user_data)
        self._users[user.id] = user

        return user
manager.py 文件源码 项目:curious 作者: SunDwarf 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def load_plugin(self, klass: typing.Type[Plugin], *args,
                          module: str = None):
        """
        Loads a plugin.
        .. note::

            The client instance will automatically be provided to the Plugin's ``__init__``.

        :param klass: The plugin class to load.
        :param args: Any args to provide to the plugin.
        :param module: The module name provided with this plugin. Only used interally.
        """
        # get the name and create the plugin object
        plugin_name = getattr(klass, "plugin_name", klass.__name__)
        instance = klass(self.client, *args)

        # call load, of course
        await instance.load()

        self.plugins[plugin_name] = instance
        if module is not None:
            self._module_plugins[module].append(instance)

        return instance
debug.py 文件源码 项目:python-devtools 作者: samuelcolvin 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def _warn(self, msg, category: Type[Warning]=RuntimeWarning):
        if self._show_warnings:
            warnings.warn(msg, category)
base_model_.py 文件源码 项目:swagger-codegen-example-python 作者: cnadiminti 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def from_dict(cls: Type[T], dikt) -> T:
        """
        Returns the dict as a model
        """
        return deserialize_model(dikt, cls)
multiple.py 文件源码 项目:Hanabi-AI 作者: MeGotsThis 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def __init__(self,
                 username: str,
                 password: str,
                 botModule: str,
                 botconfig: Mapping,
                 *args,
                 **kwargs) -> None:
        super().__init__(*args, **kwargs)
        self.username: str = username
        self.password: str = password
        module = importlib.import_module(botModule + '.bot')
        self.botCls: Type[Bot] = module.Bot  # type: ignore
        self.botconfig: Mapping = botconfig
        self.conn: socketIO_client.SocketIO
        self.game: Optional[Game] = None
card_knowledge.py 文件源码 项目:Hanabi-AI 作者: MeGotsThis 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def __copy__(self) -> 'CardKnowledge':
        cls: Type[CardKnowledge] = self.__class__
        result: CardKnowledge = cls.__new__(cls)
        result.__dict__.update(self.__dict__)
        result.cantBe = {c: self.cantBe[c][:] for c in self.bot.colors}
        return result
game.py 文件源码 项目:Hanabi-AI 作者: MeGotsThis 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def __init__(self,
                 connection: Any,
                 variant: Variant,
                 names: List[str],
                 botPosition: int,
                 botCls: Type['bot.Bot'],
                 **kwargs) -> None:
        self.connection: Any = connection
        self.variant: Variant  = variant
        self.numPlayers: int = len(names)
        self.botPosition: int = botPosition
        self.bot: bot.Bot
        self.bot = botCls(self, botPosition, names[botPosition], **kwargs)
        self.players: List[Player] = [self.bot.create_player(p, names[p])
                                      for p in range(self.numPlayers)]
        self.turnCount: int = -1
        self.deckCount: int = -1
        self.scoreCount: int = 0
        self.clueCount: int = 8
        self.strikeCount: int = 0
        self.currentPlayer: int = -1
        self.deck: Dict[int, Card] = {}
        self.discards: List[int] = []
        self.playedCards: Dict[Color, List[Card]]
        self.playedCards = {c: [] for c in variant.pile_colors}
        self.actionLog: List[str] = []
        self._lastAction: Optional[Action] = None
        self._cardMoved: Optional[int] = None
        self._cardPosition: Optional[int] = None
        self._striked: bool = False
conftest.py 文件源码 项目:fauxmo-plugins 作者: n8henrie 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def __exit__(self, exc_type: Optional[Type[BaseException]], exc_value:
                 Optional[Exception], traceback: Optional[TracebackType]) \
            -> None:
        """Terminate the server and join the thread on exit."""
        self.server.terminate()
        self.server.join()
stack.py 文件源码 项目:Lyra 作者: caterinaurban 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def __init__(self, lattice: Type, arguments: Dict[str, Any]):
        """Create a stack of elements of a lattice.

        :param lattice: type of the lattice
        """
        super().__init__()
        self._stack = [lattice(**arguments)]
sources.py 文件源码 项目:datapipelines-python 作者: meraki-analytics 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def unsupported(type: Type[T]) -> UnsupportedError:
        return UnsupportedError("The type \"{type}\" is not supported by this DataSource!".format(type=type.__name__))
sources.py 文件源码 项目:datapipelines-python 作者: meraki-analytics 项目源码 文件源码 阅读 34 收藏 0 点赞 0 评论 0
def provides(self):  # type: Union[Iterable[Type[T]], Type[Any]]
        """The types of objects the data store provides."""
        types = set()
        any_dispatch = False
        try:
            types.update(getattr(self.__class__, "get")._provides)
            any_dispatch = True
        except AttributeError:
            pass
        try:
            types.update(getattr(self.__class__, "get_many")._provides)
            any_dispatch = True
        except AttributeError:
            pass
        return types if any_dispatch else TYPE_WILDCARD
sources.py 文件源码 项目:datapipelines-python 作者: meraki-analytics 项目源码 文件源码 阅读 35 收藏 0 点赞 0 评论 0
def get(self, type: Type[T], query: Mapping[str, Any], context: PipelineContext = None) -> T:
        """Gets a query from the data source.

        Args:
            query: The query being requested.
            context: The context for the extraction (mutable).

        Returns:
            The requested object.
        """
        pass
sources.py 文件源码 项目:datapipelines-python 作者: meraki-analytics 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def get_many(self, type: Type[T], query: Mapping[str, Any], context: PipelineContext = None) -> Iterable[T]:
        """Gets a query from the data source, which contains a request for multiple objects.

        Args:
            query: The query being requested (contains a request for multiple objects).
            context: The context for the extraction (mutable).

        Returns:
            The requested objects.
        """
        pass
sources.py 文件源码 项目:datapipelines-python 作者: meraki-analytics 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def get_many(self, type: Type[T], query: Mapping[str, Any], context: PipelineContext = None) -> Iterable[T]:
        try:
            sources = self._sources[type]
        except KeyError as error:
            raise DataSource.unsupported(type) from error

        for source in sources:
            try:
                return source.get_many(type, deepcopy(query), context)
            except NotFoundError:
                continue
        raise NotFoundError()
sources.py 文件源码 项目:datapipelines-python 作者: meraki-analytics 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def get(self, type: Type[T], query: Mapping[str, Any], context: PipelineContext = None) -> T:
        try:
            sources = self._sources[type]
        except KeyError as error:
            raise DataSource.unsupported(type) from error

        for source in sources:
            try:
                return source.get(type, deepcopy(query), context)
            except NotFoundError:
                continue
        raise NotFoundError()
sinks.py 文件源码 项目:datapipelines-python 作者: meraki-analytics 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def unsupported(type: Type[T]) -> UnsupportedError:
        return UnsupportedError("The type \"{type}\" is not supported by this DataSink!".format(type=type.__name__))


问题


面经


文章

微信
公众号

扫码关注公众号