Python typing.Type() Examples

The following are 30 code examples of typing.Type(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module typing , or try the search function .
Example #1
Source File: blueprints.py    From quart with MIT License 7 votes vote down vote up
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)) 
Example #2
Source File: utils.py    From qutebrowser with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #3
Source File: cenNnFullyElasticNet.py    From decompose with MIT License 6 votes vote down vote up
def __init__(self,
                 algorithms: Type[Algorithms] = CenNnFullyElasticNetAlgorithms,
                 b: Tensor = None,
                 mu: Tensor = None,
                 betaExponential: Tensor = None,
                 tau: Tensor = None,
                 alpha: Tensor = None,
                 beta: Tensor = None,
                 tauLomax: Tensor = None,
                 properties: Properties = None) -> None:
        parameters = {"b": b,
                      "mu": mu, "tau": tau,
                      "betaExponential": betaExponential,
                      "alpha": alpha, "beta": beta, "tauLomax": tauLomax}
        Distribution.__init__(self,
                              algorithms=algorithms,
                              parameters=parameters,
                              properties=properties) 
Example #4
Source File: __init__.py    From quart with MIT License 6 votes vote down vote up
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) 
Example #5
Source File: blueprints.py    From quart with MIT License 6 votes vote down vote up
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 
Example #6
Source File: blueprints.py    From quart with MIT License 6 votes vote down vote up
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 
Example #7
Source File: base.py    From easy-faster-rcnn.pytorch with MIT License 6 votes vote down vote up
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 
Example #8
Source File: wrapped.py    From OpenFermion-Cirq with Apache License 2.0 6 votes vote down vote up
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) 
Example #9
Source File: source.py    From tomlkit with MIT License 6 votes vote down vote up
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 
Example #10
Source File: expressions.py    From matchpy with MIT License 6 votes vote down vote up
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 
Example #11
Source File: cenNnFullyElasticNetCond.py    From decompose with MIT License 6 votes vote down vote up
def __init__(self,
                 algorithms: Type[Algorithms] = CenNnFullyElasticNetAlgorithms,
                 b: Tensor = None,
                 mu: Tensor = None,
                 tau: Tensor = None,
                 betaExponential: Tensor = None,
                 beta: Tensor = None,
                 properties: Properties = None) -> None:
        parameters = {"b": b,
                      "mu": mu, "tau": tau,
                      "betaExponential": betaExponential,
                      "beta": beta}
        Distribution.__init__(self,
                              algorithms=algorithms,
                              parameters=parameters,
                              properties=properties) 
Example #12
Source File: imports.py    From python-clean-architecture with MIT License 6 votes vote down vote up
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 
Example #13
Source File: descriptors.py    From python-clean-architecture with MIT License 6 votes vote down vote up
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'),
            ) 
Example #14
Source File: importer.py    From pydfs-lineup-optimizer with MIT License 6 votes vote down vote up
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 
Example #15
Source File: LocalData.py    From gphotos-sync with MIT License 6 votes vote down vote up
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 
Example #16
Source File: expressions.py    From matchpy with MIT License 6 votes vote down vote up
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) 
Example #17
Source File: compound.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
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) 
Example #18
Source File: compound.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
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) 
Example #19
Source File: exponential.py    From decompose with MIT License 5 votes vote down vote up
def __init__(self,
                 algorithms: Type[Algorithms] = ExponentialAlgorithms,
                 beta: Tensor = None,
                 properties: Properties = None) -> None:
        parameters = {"beta": beta}
        Distribution.__init__(self,
                              algorithms=algorithms,
                              parameters=parameters,
                              properties=properties) 
Example #20
Source File: nnNormal.py    From decompose with MIT License 5 votes vote down vote up
def __init__(self,
                 algorithms: Type[Algorithms] = NnNormalAlgorithms,
                 mu: Tensor = None,
                 tau: Tensor = None,
                 properties: Properties = None) -> None:
        parameters = {"mu": mu, "tau": tau}
        Distribution.__init__(self,
                              algorithms=algorithms,
                              parameters=parameters,
                              properties=properties) 
Example #21
Source File: cenNormalRankOne.py    From decompose with MIT License 5 votes vote down vote up
def __init__(self,
                 algorithms: Type[Algorithms] = CenNormalRankOneAlgorithms,
                 tau0: Tensor = None,
                 tau1: Tensor = None,
                 properties: Properties = None) -> None:
        parameters = {"tau0": tau0, "tau1": tau1}
        Distribution.__init__(self,
                              algorithms=algorithms,
                              parameters=parameters,
                              properties=properties) 
Example #22
Source File: cenNormal.py    From decompose with MIT License 5 votes vote down vote up
def __init__(self,
                 algorithms: Type[Algorithms] = CenNormalAlgorithms,
                 tau: Tensor = None,
                 properties: Properties = None) -> None:
        parameters = {"tau": tau}
        Distribution.__init__(self,
                              algorithms=algorithms,
                              parameters=parameters,
                              properties=properties) 
Example #23
Source File: cenNnNormal.py    From decompose with MIT License 5 votes vote down vote up
def __init__(self,
                 algorithms: Type[Algorithms] = CenNnNormalAlgorithms,
                 tau: Tensor = None,
                 properties: Properties = None) -> None:
        parameters = {"tau": tau}
        Distribution.__init__(self,
                              algorithms=algorithms,
                              parameters=parameters,
                              properties=properties) 
Example #24
Source File: docopt.py    From brownie with MIT License 5 votes vote down vote up
def __init__(
        self,
        source: Union[List[str], str],
        error: Union[Type[DocoptExit], Type[DocoptLanguageError]] = DocoptExit,
    ) -> None:
        if isinstance(source, list):
            self += source
        else:
            self += source.split()
        self.error = error 
Example #25
Source File: exceptions.py    From brownie with MIT License 5 votes vote down vote up
def __init__(self, e: Type[psutil.Popen]) -> None:
        err = [i["formattedMessage"] for i in yaml.safe_load(e.stdout_data)["errors"]]
        super().__init__("Compiler returned the following errors:\n\n" + "\n".join(err)) 
Example #26
Source File: source.py    From tomlkit with MIT License 5 votes vote down vote up
def parse_error(
        self, exception=ParseError, *args
    ):  # type: (Type[ParseError], Any) -> ParseError
        """
        Creates a generic "parse error" at the current position.
        """
        line, col = self._to_linecol()

        return exception(line, col, *args) 
Example #27
Source File: browsertab.py    From qutebrowser with GNU General Public License v3.0 5 votes vote down vote up
def _on_navigation_request(
            self,
            navigation: usertypes.NavigationRequest
    ) -> None:
        """Handle common acceptNavigationRequest code."""
        url = utils.elide(navigation.url.toDisplayString(), 100)
        log.webview.debug("navigation request: url {}, type {}, is_main_frame "
                          "{}".format(url,
                                      navigation.navigation_type,
                                      navigation.is_main_frame))

        if navigation.is_main_frame:
            self.data.last_navigation = navigation

        if not navigation.url.isValid():
            # Also a WORKAROUND for missing IDNA 2008 support in QUrl, see
            # https://bugreports.qt.io/browse/QTBUG-60364

            if navigation.navigation_type == navigation.Type.link_clicked:
                msg = urlutils.get_errstring(navigation.url,
                                             "Invalid link clicked")
                message.error(msg)
                self.data.open_target = usertypes.ClickTarget.normal

            log.webview.debug("Ignoring invalid URL {} in "
                              "acceptNavigationRequest: {}".format(
                                  navigation.url.toDisplayString(),
                                  navigation.url.errorString()))
            navigation.accepted = False 
Example #28
Source File: browsertab.py    From qutebrowser with GNU General Public License v3.0 5 votes vote down vote up
def _set_load_status(self, val: usertypes.LoadStatus) -> None:
        """Setter for load_status."""
        if not isinstance(val, usertypes.LoadStatus):
            raise TypeError("Type {} is no LoadStatus member!".format(val))
        log.webview.debug("load status for {}: {}".format(repr(self), val))
        self._load_status = val
        self.load_status_changed.emit(val) 
Example #29
Source File: debug.py    From qutebrowser with GNU General Public License v3.0 5 votes vote down vote up
def __exit__(self,
                 _exc_type: 'typing.Optional[typing.Type[BaseException]]',
                 _exc_val: typing.Optional[BaseException],
                 _exc_tb: typing.Optional[types.TracebackType]) -> None:
        assert self._started is not None
        finished = datetime.datetime.now()
        delta = (finished - self._started).total_seconds()
        self._logger.debug("{} took {} seconds.".format(
            self._action.capitalize(), delta)) 
Example #30
Source File: debug.py    From qutebrowser with GNU General Public License v3.0 5 votes vote down vote up
def qenum_key(base: typing.Type,
              value: typing.Union[int, sip.simplewrapper],
              add_base: bool = False,
              klass: typing.Type = None) -> str:
    """Convert a Qt Enum value to its key as a string.

    Args:
        base: The object the enum is in, e.g. QFrame.
        value: The value to get.
        add_base: Whether the base should be added to the printed name.
        klass: The enum class the value belongs to.
               If None, the class will be auto-guessed.

    Return:
        The key associated with the value as a string if it could be found.
        The original value as a string if not.
    """
    if klass is None:
        klass = value.__class__
        if klass == int:
            raise TypeError("Can't guess enum class of an int!")

    try:
        idx = base.staticMetaObject.indexOfEnumerator(klass.__name__)
        meta_enum = base.staticMetaObject.enumerator(idx)
        ret = meta_enum.valueToKey(int(value))  # type: ignore[arg-type]
    except AttributeError:
        ret = None

    if ret is None:
        for name, obj in vars(base).items():
            if isinstance(obj, klass) and obj == value:
                ret = name
                break
        else:
            ret = '0x{:04x}'.format(int(value))  # type: ignore[arg-type]

    if add_base and hasattr(base, '__name__'):
        return '.'.join([base.__name__, ret])
    else:
        return ret