当前位置: 首页>>代码示例>>Python>>正文


Python typing.Type方法代码示例

本文整理汇总了Python中typing.Type方法的典型用法代码示例。如果您正苦于以下问题:Python typing.Type方法的具体用法?Python typing.Type怎么用?Python typing.Type使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在typing的用法示例。


在下文中一共展示了typing.Type方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: __get__

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Type [as 别名]
def __get__(self, instance: t.Any, owner: t.Type) -> t.Any:
        if instance is None:
            return self
        container = get_di_container(instance)
        if not container:
            raise DIErrors.NO_CONTAINER_PROVIDED.with_params(
                class_name=instance.__class__.__qualname__,
                attribute=self.label
            )
        context = self.context.determine(instance)
        try:
            return context.get(container=container)
        except ConfigError as e:
            raise e.with_params(
                class_name=instance.__class__.__qualname__,
                attribute=self.label,
                context=e.params.get('context'),
            ) 
开发者ID:pcah,项目名称:python-clean-architecture,代码行数:20,代码来源:descriptors.py

示例2: import_dotted_path

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Type [as 别名]
def import_dotted_path(dotted_path: str) -> t.Type:
    """
    Import a dotted module path and return the attribute/class designated by
    the last name in the path. Raise ImportError if the import failed.

    Code taken from: django.utils.module_loading,import_string v 1.9
    """
    try:
        module_path, qual_name = dotted_path.rsplit(':', 1) \
            if ':' in dotted_path else dotted_path.rsplit('.', 1)
    except ValueError as e:
        msg = "'%s' doesn't look like a module path" % dotted_path
        raise ImportError(msg) from e

    obj = import_module(module_path)

    try:
        for chunk in qual_name.split('.'):
            obj = getattr(obj, chunk)
    except AttributeError as e:
        msg = "Module '%s' does not define a '%s' attribute/class" % (
            module_path, qual_name)
        raise ImportError(msg) from e
    return obj 
开发者ID:pcah,项目名称:python-clean-architecture,代码行数:26,代码来源:imports.py

示例3: assert_eigengate_implements_consistent_protocols

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Type [as 别名]
def assert_eigengate_implements_consistent_protocols(
        eigen_gate_type: Type[cirq.EigenGate],
        *,
        exponents: Sequence[Union[sympy.Basic, float]] = (
            0, 1, -1, 0.25, -0.5, 0.1, sympy.Symbol('s')),
        global_shifts: Sequence[float] = (0, -0.5, 0.1),
        qubit_count: Optional[int] = None,
        ignoring_global_phase: bool=False,
        setup_code: str = _setup_code,
        global_vals: Optional[Dict[str, Any]] = None,
        local_vals: Optional[Dict[str, Any]] = None) -> None:
    """Checks that an EigenGate subclass is internally consistent and has a
    good __repr__."""

    cirq.testing.assert_eigengate_implements_consistent_protocols(
        eigen_gate_type,
        exponents=exponents,
        global_shifts=global_shifts,
        qubit_count=qubit_count,
        ignoring_global_phase=ignoring_global_phase,
        setup_code=setup_code,
        global_vals=global_vals,
        local_vals=local_vals) 
开发者ID:quantumlib,项目名称:OpenFermion-Cirq,代码行数:25,代码来源:wrapped.py

示例4: errorhandler

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Type [as 别名]
def errorhandler(self, error: Union[Type[Exception], int]) -> Callable:
        """Add an error handler function to the Blueprint.

        This is designed to be used as a decorator, and has the same
        arguments as :meth:`~quart.Quart.errorhandler`. It applies
        only to errors that originate in routes in this blueprint. An
        example usage,

        .. code-block:: python

            blueprint = Blueprint(__name__)
            @blueprint.errorhandler(404)
            def not_found():
                ...

        """

        def decorator(func: Callable) -> Callable:
            self.register_error_handler(error, func)
            return func

        return decorator 
开发者ID:pgjones,项目名称:quart,代码行数:24,代码来源:blueprints.py

示例5: app_errorhandler

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Type [as 别名]
def app_errorhandler(self, error: Union[Type[Exception], int]) -> Callable:
        """Add an error handler function to the App.

        This is designed to be used as a decorator, and has the same
        arguments as :meth:`~quart.Quart.errorhandler`. It applies
        only to all errors. An example usage,

        .. code-block:: python

            blueprint = Blueprint(__name__)
            @blueprint.app_errorhandler(404)
            def not_found():
                ...
        """

        def decorator(func: Callable) -> Callable:
            self.record_once(lambda state: state.app.register_error_handler(error, func))
            return func

        return decorator 
开发者ID:pgjones,项目名称:quart,代码行数:22,代码来源:blueprints.py

示例6: register_error_handler

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Type [as 别名]
def register_error_handler(self, error: Union[Type[Exception], int], func: Callable) -> None:
        """Add an error handler function to the blueprint.

        This is designed to be used on the blueprint directly, and
        has the same arguments as
        :meth:`~quart.Quart.register_error_handler`. An example usage,

        .. code-block:: python

            def not_found():
                ...

            blueprint = Blueprint(__name__)
            blueprint.register_error_handler(404, not_found)
        """
        self.record_once(lambda state: state.app.register_error_handler(error, func, self.name)) 
开发者ID:pgjones,项目名称:quart,代码行数:18,代码来源:blueprints.py

示例7: dumps

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Type [as 别名]
def dumps(object_: Any, app: Optional["Quart"] = None, **kwargs: Any) -> str:
    json_encoder: Type[json.JSONEncoder] = JSONEncoder
    if app is None and _app_ctx_stack.top is not None:  # has_app_context requires a circular import
        app = current_app._get_current_object()

    if app is not None:
        json_encoder = app.json_encoder
        if _request_ctx_stack.top is not None:  # has_request_context requires a circular import
            blueprint = app.blueprints.get(request.blueprint)
            if blueprint is not None and blueprint.json_encoder is not None:
                json_encoder = blueprint.json_encoder
        kwargs.setdefault("ensure_ascii", app.config["JSON_AS_ASCII"])
        kwargs.setdefault("sort_keys", app.config["JSON_SORT_KEYS"])
    kwargs.setdefault("sort_keys", True)
    kwargs.setdefault("cls", json_encoder)

    return json.dumps(object_, **kwargs) 
开发者ID:pgjones,项目名称:quart,代码行数:19,代码来源:__init__.py

示例8: from_name

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Type [as 别名]
def from_name(name: str) -> Type['Base']:
        if name == 'voc2007':
            from dataset.voc2007 import VOC2007
            return VOC2007
        elif name == 'coco2017':
            from dataset.coco2017 import COCO2017
            return COCO2017
        elif name == 'voc2007-cat-dog':
            from dataset.voc2007_cat_dog import VOC2007CatDog
            return VOC2007CatDog
        elif name == 'coco2017-person':
            from dataset.coco2017_person import COCO2017Person
            return COCO2017Person
        elif name == 'coco2017-car':
            from dataset.coco2017_car import COCO2017Car
            return COCO2017Car
        elif name == 'coco2017-animal':
            from dataset.coco2017_animal import COCO2017Animal
            return COCO2017Animal
        else:
            raise ValueError 
开发者ID:potterhsu,项目名称:easy-faster-rcnn.pytorch,代码行数:23,代码来源:base.py

示例9: symbol

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Type [as 别名]
def symbol(name: str=None, symbol_type: Type[Symbol]=Symbol) -> 'SymbolWildcard':
        """Create a `SymbolWildcard` that matches a single `Symbol` argument.

        Args:
            name:
                Optional variable name for the wildcard.
            symbol_type:
                An optional subclass of `Symbol` to further limit which kind of symbols are
                matched by the wildcard.

        Returns:
            A `SymbolWildcard` that matches the *symbol_type*.
        """
        if isinstance(name, type) and issubclass(name, Symbol) and symbol_type is Symbol:
            return SymbolWildcard(name)
        return SymbolWildcard(symbol_type, variable_name=name) 
开发者ID:HPAC,项目名称:matchpy,代码行数:18,代码来源:expressions.py

示例10: __init__

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Type [as 别名]
def __init__(self, symbol_type: Type[Symbol]=Symbol, variable_name=None) -> None:
        """
        Args:
            symbol_type:
                A subclass of `Symbol` to constrain what the wildcard matches.
                If not specified, the wildcard will match any `Symbol`.

        Raises:
            TypeError: if *symbol_type* is not a subclass of `Symbol`.
        """
        super().__init__(1, True, variable_name)

        if not issubclass(symbol_type, Symbol):
            raise TypeError("The type constraint must be a subclass of Symbol")

        self.symbol_type = symbol_type 
开发者ID:HPAC,项目名称:matchpy,代码行数:18,代码来源:expressions.py

示例11: build_fanduel_single_game_importer

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Type [as 别名]
def build_fanduel_single_game_importer(mvp=True, star=False, pro=False) -> Type[FanDuelCSVImporter]:
    class FanDuelSingleGameCSVImporter(FanDuelCSVImporter):  # pragma: nocover
        def import_players(self):
            players = super().import_players()
            extra_players = []
            for player in players:
                if mvp:
                    mvp_player = deepcopy(player)
                    mvp_player.fppg *= 2
                    mvp_player.rank = PlayerRank.MVP
                    extra_players.append(mvp_player)
                if star:
                    star_player = deepcopy(player)
                    star_player.fppg *= 1.5
                    star_player.rank = PlayerRank.STAR
                    extra_players.append(star_player)
                if pro:
                    pro_player = deepcopy(player)
                    pro_player.fppg *= 1.2
                    pro_player.rank = PlayerRank.PRO
                    extra_players.append(pro_player)
            players.extend(extra_players)
            return players
    return FanDuelSingleGameCSVImporter 
开发者ID:DimaKudosh,项目名称:pydfs-lineup-optimizer,代码行数:26,代码来源:importer.py

示例12: get_file_by_path

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Type [as 别名]
def get_file_by_path(
        self, row_type: Type[DbRow], folder: Path, name: str
    ) -> DatabaseMedia:
        """
        Search for a media item by filename, this applies to any of the
        BaseMedia/DbRow derived class pairs
        """
        query = "SELECT {0} FROM {1} WHERE Path = ?" " AND FileName = ?;".format(
            row_type.columns, row_type.table
        )
        self.cur.execute(query, (str(folder), name))
        record = self.cur.fetchone()
        return row_type(record).to_media()

    # functions for managing the SyncFiles Table ##############################

    # todo this could be generic and support Albums and LocalFiles too 
开发者ID:gilesknap,项目名称:gphotos-sync,代码行数:19,代码来源:LocalData.py

示例13: __init__

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Type [as 别名]
def __init__(self,
                 model_spec,  # type: typing.Type[T]
                 **kwargs):
        # type: (...) -> T

        if isinstance(model_spec, ModelMeta):
            self._model_class = model_spec
            self.model_name = self.model_class.__name__
        elif isinstance(model_spec, string_type):
            self._model_class = None
            self.model_name = model_spec
        else:
            raise TypeError("ModelType: Expected a model, got an argument "
                            "of the type '{}'.".format(model_spec.__class__.__name__))

        super(ModelType, self).__init__(**kwargs) 
开发者ID:remg427,项目名称:misp42splunk,代码行数:18,代码来源:compound.py

示例14: raises

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Type [as 别名]
def raises(exc: ('typing.Union['  # pylint: disable=bad-docstring-quotes
                 '    typing.Type[BaseException], '
                 '    typing.Tuple[typing.Type[BaseException]]]'),
           func: typing.Callable,
           *args: typing.Any) -> bool:
    """Check if a function raises a given exception.

    Args:
        exc: A single exception or an iterable of exceptions.
        func: A function to call.
        *args: The arguments to pass to the function.

    Returns:
        True if the exception was raised, False otherwise.
    """
    try:
        func(*args)
    except exc:
        return True
    else:
        return False 
开发者ID:qutebrowser,项目名称:qutebrowser,代码行数:23,代码来源:utils.py

示例15: inc

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Type [as 别名]
def inc(self, exception=None):  # type: (Optional[Type[ParseError]]) -> bool
        """
        Increments the parser if the end of the input has not been reached.
        Returns whether or not it was able to advance.
        """
        try:
            self._idx, self._current = next(self._chars)

            return True
        except StopIteration:
            self._idx = len(self)
            self._current = self.EOF
            if exception:
                raise self.parse_error(exception)

            return False 
开发者ID:sdispater,项目名称:tomlkit,代码行数:18,代码来源:source.py


注:本文中的typing.Type方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。