Python typing.NoReturn() Examples

The following are 30 code examples of typing.NoReturn(). 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: clusters.py    From mabwiser with Apache License 2.0 7 votes vote down vote up
def fit(self, decisions: np.ndarray, rewards: np.ndarray,
            contexts: Optional[np.ndarray] = None) -> NoReturn:

        # Set the historical data for prediction
        self.decisions = decisions
        self.contexts = contexts

        # Binarize the rewards if using Thompson Sampling
        if isinstance(self.lp_list[0], _ThompsonSampling) and self.lp_list[0].binarizer:
            for lp in self.lp_list:
                lp.is_contextual_binarized = False
            self.rewards = self.lp_list[0]._get_binary_rewards(decisions, rewards)
            for lp in self.lp_list:
                lp.is_contextual_binarized = True
        else:
            self.rewards = rewards

        self._fit_operation() 
Example #2
Source File: util.py    From opendevops with GNU General Public License v3.0 6 votes vote down vote up
def raise_exc_info(
    exc_info,  # type: Tuple[Optional[type], Optional[BaseException], Optional[TracebackType]]
):
    # type: (...) -> typing.NoReturn
    #
    # This function's type annotation must use comments instead of
    # real annotations because typing.NoReturn does not exist in
    # python 3.5's typing module. The formatting is funky because this
    # is apparently what flake8 wants.
    try:
        if exc_info[1] is not None:
            raise exc_info[1].with_traceback(exc_info[2])
        else:
            raise TypeError("raise_exc_info called with no exception")
    finally:
        # Clear the traceback reference from our stack frame to
        # minimize circular references that slow down GC.
        exc_info = (None, None, None) 
Example #3
Source File: _kulczynski_i.py    From abydos with GNU General Public License v3.0 6 votes vote down vote up
def sim(self, *args: Any, **kwargs: Any) -> NoReturn:
        """Raise exception when called.

        Parameters
        ----------
        *args
            Variable length argument list
        **kwargs
            Arbitrary keyword arguments

        Raises
        ------
        NotImplementedError
            Method disabled for Kulczynski I similarity.


        .. versionadded:: 0.3.6

        """
        raise NotImplementedError(
            'Method disabled for Kulczynski I similarity.'
        ) 
Example #4
Source File: test_app.py    From quart with MIT License 6 votes vote down vote up
def test_app_handle_request_asyncio_cancelled_error() -> None:
    app = Quart(__name__)

    @app.route("/")
    async def index() -> NoReturn:
        raise asyncio.CancelledError()

    request = app.request_class(
        "GET",
        "http",
        "/",
        b"",
        Headers([("host", "quart.com")]),
        "",
        "1.1",
        send_push_promise=no_op_push,
    )
    with pytest.raises(asyncio.CancelledError):
        await app.handle_request(request) 
Example #5
Source File: outcomes.py    From pytest with MIT License 6 votes vote down vote up
def skip(msg: str = "", *, allow_module_level: bool = False) -> "NoReturn":
    """
    Skip an executing test with the given message.

    This function should be called only during testing (setup, call or teardown) or
    during collection by using the ``allow_module_level`` flag.  This function can
    be called in doctests as well.

    :kwarg bool allow_module_level: allows this function to be called at
        module level, skipping the rest of the module. Default to False.

    .. note::
        It is better to use the :ref:`pytest.mark.skipif ref` marker when possible to declare a test to be
        skipped under certain conditions like mismatching platforms or
        dependencies.
        Similarly, use the ``# doctest: +SKIP`` directive (see `doctest.SKIP
        <https://docs.python.org/3/library/doctest.html#doctest.SKIP>`_)
        to skip a doctest statically.
    """
    __tracebackhide__ = True
    raise Skipped(msg=msg, allow_module_level=allow_module_level) 
Example #6
Source File: _kulczynski_i.py    From abydos with GNU General Public License v3.0 6 votes vote down vote up
def dist(self, *args: Any, **kwargs: Any) -> NoReturn:
        """Raise exception when called.

        Parameters
        ----------
        *args
            Variable length argument list
        **kwargs
            Arbitrary keyword arguments

        Raises
        ------
        NotImplementedError
            Method disabled for Kulczynski I similarity.


        .. versionadded:: 0.3.6

        """
        raise NotImplementedError(
            'Method disabled for Kulczynski I similarity.'
        ) 
Example #7
Source File: _sokal_sneath_iii.py    From abydos with GNU General Public License v3.0 6 votes vote down vote up
def sim(self, *args: Any, **kwargs: Any) -> NoReturn:
        """Raise exception when called.

        Parameters
        ----------
        *args
            Variable length argument list
        **kwargs
            Arbitrary keyword arguments

        Raises
        ------
        NotImplementedError
            Method disabled for Sokal & Sneath III similarity.


        .. versionadded:: 0.3.6

        """
        raise NotImplementedError(
            'Method disabled for Sokal & Sneath III similarity.'
        ) 
Example #8
Source File: _millar.py    From abydos with GNU General Public License v3.0 6 votes vote down vote up
def dist(self, *args: Any, **kwargs: Any) -> NoReturn:
        """Raise exception when called.

        Parameters
        ----------
        *args
            Variable length argument list
        **kwargs
            Arbitrary keyword arguments

        Raises
        ------
        NotImplementedError
            Method disabled for Millar dissimilarity.


        .. versionadded:: 0.3.6

        """
        raise NotImplementedError('Method disabled for Millar dissimilarity.') 
Example #9
Source File: _millar.py    From abydos with GNU General Public License v3.0 6 votes vote down vote up
def sim(self, *args: Any, **kwargs: Any) -> NoReturn:
        """Raise exception when called.

        Parameters
        ----------
        *args
            Variable length argument list
        **kwargs
            Arbitrary keyword arguments

        Raises
        ------
        NotImplementedError
            Method disabled for Millar dissimilarity.


        .. versionadded:: 0.3.6

        """
        raise NotImplementedError('Method disabled for Millar dissimilarity.') 
Example #10
Source File: clusters.py    From mabwiser with Apache License 2.0 6 votes vote down vote up
def partial_fit(self, decisions: np.ndarray, rewards: np.ndarray,
                    contexts: Optional[np.ndarray] = None) -> NoReturn:

        # Binarize the rewards if using Thompson Sampling
        if isinstance(self.lp_list[0], _ThompsonSampling) and self.lp_list[0].binarizer:
            for lp in self.lp_list:
                lp.is_contextual_binarized = False
            rewards = self.lp_list[0]._get_binary_rewards(decisions, rewards)
            for lp in self.lp_list:
                lp.is_contextual_binarized = True

        # Add more historical data for prediction
        self.decisions = np.concatenate((self.decisions, decisions))
        self.contexts = np.concatenate((self.contexts, contexts))
        self.rewards = np.concatenate((self.rewards, rewards))

        self._fit_operation() 
Example #11
Source File: _morisita.py    From abydos with GNU General Public License v3.0 6 votes vote down vote up
def dist(self, *args: Any, **kwargs: Any) -> NoReturn:
        """Raise exception when called.

        Parameters
        ----------
        *args
            Variable length argument list
        **kwargs
            Arbitrary keyword arguments

        Raises
        ------
        NotImplementedError
            Method disabled for Morisita similarity.


        .. versionadded:: 0.3.6

        """
        raise NotImplementedError('Method disabled for Morisita similarity.') 
Example #12
Source File: _morisita.py    From abydos with GNU General Public License v3.0 6 votes vote down vote up
def sim(self, *args: Any, **kwargs: Any) -> NoReturn:
        """Raise exception when called.

        Parameters
        ----------
        *args
            Variable length argument list
        **kwargs
            Arbitrary keyword arguments

        Raises
        ------
        NotImplementedError
            Method disabled for Morisita similarity.


        .. versionadded:: 0.3.6

        """
        raise NotImplementedError('Method disabled for Morisita similarity.') 
Example #13
Source File: webserver_command.py    From airflow with Apache License 2.0 6 votes vote down vote up
def start(self) -> NoReturn:
        """
        Starts monitoring the webserver.
        """
        try:  # pylint: disable=too-many-nested-blocks
            self._wait_until_true(
                lambda: self.num_workers_expected == self._get_num_workers_running(),
                timeout=self.master_timeout
            )
            while True:
                if not self.gunicorn_master_proc.is_running():
                    sys.exit(1)
                self._check_workers()
                # Throttle loop
                sleep(1)

        except (AirflowWebServerTimeout, OSError) as err:
            self.log.error(err)
            self.log.error("Shutting down webserver")
            try:
                self.gunicorn_master_proc.terminate()
                self.gunicorn_master_proc.wait()
            finally:
                sys.exit(1) 
Example #14
Source File: util.py    From teleport with Apache License 2.0 6 votes vote down vote up
def raise_exc_info(
    exc_info,  # type: Tuple[Optional[type], Optional[BaseException], Optional[TracebackType]]
):
    # type: (...) -> typing.NoReturn
    #
    # This function's type annotation must use comments instead of
    # real annotations because typing.NoReturn does not exist in
    # python 3.5's typing module. The formatting is funky because this
    # is apparently what flake8 wants.
    try:
        if exc_info[1] is not None:
            raise exc_info[1].with_traceback(exc_info[2])
        else:
            raise TypeError("raise_exc_info called with no exception")
    finally:
        # Clear the traceback reference from our stack frame to
        # minimize circular references that slow down GC.
        exc_info = (None, None, None) 
Example #15
Source File: util.py    From teleport with Apache License 2.0 6 votes vote down vote up
def raise_exc_info(
    exc_info,  # type: Tuple[Optional[type], Optional[BaseException], Optional[TracebackType]]
):
    # type: (...) -> typing.NoReturn
    #
    # This function's type annotation must use comments instead of
    # real annotations because typing.NoReturn does not exist in
    # python 3.5's typing module. The formatting is funky because this
    # is apparently what flake8 wants.
    try:
        if exc_info[1] is not None:
            raise exc_info[1].with_traceback(exc_info[2])
        else:
            raise TypeError("raise_exc_info called with no exception")
    finally:
        # Clear the traceback reference from our stack frame to
        # minimize circular references that slow down GC.
        exc_info = (None, None, None) 
Example #16
Source File: make.py    From httprunner with Apache License 2.0 6 votes vote down vote up
def format_pytest_with_black(*python_paths: Text) -> NoReturn:
    logger.info("format pytest cases with black ...")
    try:
        if is_support_multiprocessing() or len(python_paths) <= 1:
            subprocess.run(["black", *python_paths])
        else:
            logger.warning(
                f"this system does not support multiprocessing well, format files one by one ..."
            )
            [subprocess.run(["black", path]) for path in python_paths]
    except subprocess.CalledProcessError as ex:
        capture_exception(ex)
        logger.error(ex)
        sys.exit(1)
    except FileNotFoundError:
        err_msg = """
missing dependency tool: black
install black manually and try again:
$ pip install black
"""
        logger.error(err_msg)
        sys.exit(1) 
Example #17
Source File: window.py    From ibis with Apache License 2.0 5 votes vote down vote up
def get_aggcontext(
    window, *, operand, operand_dtype, parent, group_by, order_by
) -> NoReturn:
    raise NotImplementedError(
        f"get_aggcontext is not implemented for {type(window).__name__}"
    ) 
Example #18
Source File: fixtures.py    From pytest with MIT License 5 votes vote down vote up
def fail_fixturefunc(fixturefunc, msg: str) -> "NoReturn":
    fs, lineno = getfslineno(fixturefunc)
    location = "{}:{}".format(fs, lineno + 1)
    source = _pytest._code.Source(fixturefunc)
    fail(msg + ":\n\n" + str(source.indent()) + "\n" + location, pytrace=False) 
Example #19
Source File: __init__.py    From httprunner with Apache License 2.0 5 votes vote down vote up
def prepare_upload_step(step: TStep, functions: FunctionsMapping) -> "NoReturn":
    """ preprocess for upload test
        replace `upload` info with MultipartEncoder

    Args:
        step: teststep
            {
                "variables": {},
                "request": {
                    "url": "http://httpbin.org/upload",
                    "method": "POST",
                    "headers": {
                        "Cookie": "session=AAA-BBB-CCC"
                    },
                    "upload": {
                        "file": "data/file_to_upload"
                        "md5": "123"
                    }
                }
            }
        functions: functions mapping

    """
    if not step.request.upload:
        return

    ensure_upload_ready()
    params_list = []
    for key, value in step.request.upload.items():
        step.variables[key] = value
        params_list.append(f"{key}=${key}")

    params_str = ", ".join(params_list)
    step.variables["m_encoder"] = "${multipart_encoder(" + params_str + ")}"

    # parse variables
    step.variables = parse_variables_mapping(step.variables, functions)

    step.request.headers["Content-Type"] = "${multipart_content_type($m_encoder)}"

    step.request.data = "$m_encoder" 
Example #20
Source File: runner.py    From httprunner with Apache License 2.0 5 votes vote down vote up
def __init_tests__(self) -> NoReturn:
        self.__config = self.config.perform()
        self.__teststeps = []
        for step in self.teststeps:
            self.__teststeps.append(step.perform()) 
Example #21
Source File: exceptions.py    From quart with MIT License 5 votes vote down vote up
def abort(
    status_or_response: Union[int, Response],
    description: Optional[str] = None,
    name: Optional[str] = None,
) -> NoReturn:
    """Raises a HTTPException with the status code or response given.

    This can be used either with a status code (with optional
    description and name) or with a Response object. The latter allows
    for an abort (after response functions etc aren't called) with a
    custom response.

    .. code-block:: python

        abort(403)
        abort(Response("Message"))

    """
    if description is None and name is None and not isinstance(status_or_response, int):
        raise _AbortResponseException(status_or_response)
    else:
        status_or_response = cast(int, status_or_response)
        error_class = all_http_exceptions.get(status_or_response)
        if error_class is None:
            raise HTTPException(status_or_response, description or "Unknown", name or "Unknown")
        else:
            error = error_class()
            if description is not None:
                error.description = description
            if name is not None:
                error.name = name
            raise error 
Example #22
Source File: make.py    From httprunner with Apache License 2.0 5 votes vote down vote up
def __ensure_testcase_module(path: Text) -> NoReturn:
    """ ensure pytest files are in python module, generate __init__.py on demand
    """
    init_file = os.path.join(os.path.dirname(path), "__init__.py")
    if os.path.isfile(init_file):
        return

    with open(init_file, "w", encoding="utf-8") as f:
        f.write("# NOTICE: Generated By HttpRunner. DO NOT EDIT!\n") 
Example #23
Source File: dataset_view.py    From QCPortal with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_entries(self) -> NoReturn:
        raise NotImplementedError() 
Example #24
Source File: dataset_view.py    From QCPortal with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_molecules(self, indexes: List[Union[ObjectId, int]]) -> NoReturn:
        raise NotImplementedError() 
Example #25
Source File: dataset_view.py    From QCPortal with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_values(self, queries: List[Dict[str, Union[str, bool]]]) -> NoReturn:
        raise NotImplementedError() 
Example #26
Source File: outcomes.py    From pytest with MIT License 5 votes vote down vote up
def fail(msg: str = "", pytrace: bool = True) -> "NoReturn":
    """
    Explicitly fail an executing test with the given message.

    :param str msg: the message to show the user as reason for the failure.
    :param bool pytrace: if false the msg represents the full failure information and no
        python traceback will be reported.
    """
    __tracebackhide__ = True
    raise Failed(msg=msg, pytrace=pytrace) 
Example #27
Source File: dataset_view.py    From QCPortal with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def list_values(self) -> NoReturn:
        raise NotImplementedError() 
Example #28
Source File: dataset_view.py    From QCPortal with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def write(self, ds: Dataset) -> NoReturn:
        raise NotImplementedError() 
Example #29
Source File: connection.py    From aioapns with Apache License 2.0 5 votes vote down vote up
def __init__(self,
                 apns_topic: str,
                 loop: Optional[asyncio.AbstractEventLoop] = None,
                 on_connection_lost: Optional[
                     Callable[['APNsBaseClientProtocol'], NoReturn]] = None,
                 auth_provider: Optional[AuthorizationHeaderProvider] = None):
        super(APNsBaseClientProtocol, self).__init__()
        self.apns_topic = apns_topic
        self.loop = loop or asyncio.get_event_loop()
        self.on_connection_lost = on_connection_lost
        self.auth_provider = auth_provider

        self.requests = {}
        self.request_streams = {}
        self.request_statuses = {}
        self.inactivity_timer = None 
Example #30
Source File: run.py    From virtme with GNU General Public License v2.0 5 votes vote down vote up
def arg_fail(message, show_usage=True) -> NoReturn:
    print(message)
    if show_usage:
        _ARGPARSER.print_usage()
    sys.exit(1)