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


Python typing.Union方法代码示例

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


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

示例1: get_listeners

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Union [as 别名]
def get_listeners(
        self, event_name=None
    ):  # type: (str) -> Union[List[Callable], Dict[str, Callable]]
        if event_name is not None:
            if event_name not in self._listeners:
                return []

            if event_name not in self._sorted:
                self._sort_listeners(event_name)

            return self._sorted[event_name]

        for event_name, event_listeners in self._listeners.items():
            if event_name not in self._sorted:
                self._sort_listeners(event_name)

        return self._sorted 
开发者ID:sdispater,项目名称:clikit,代码行数:19,代码来源:event_dispatcher.py

示例2: check_authentication_response

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Union [as 别名]
def check_authentication_response() -> Union[Response, None]:
    """
    Return the response as per the authentication requirements.
    """
    if get_authentication():
        if get_token():
            token = check_token(request, get_session())
            if not token:
                if request.authorization is None:
                    return failed_authentication(False)
                else:
                    return verify_user()
        elif request.authorization is None:
            return failed_authentication(False)
        else:
            return verify_user()
    else:
        return None 
开发者ID:HTTP-APIs,项目名称:hydrus,代码行数:20,代码来源:auth.py

示例3: filename_to_url

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Union [as 别名]
def filename_to_url(filename: str, cache_dir: Union[str, Path] = None) -> Tuple[str, str]:
    """
    Return the url and etag (which may be ``None``) stored for `filename`.
    Raise ``FileNotFoundError`` if `filename` or its stored metadata do not exist.
    """
    if cache_dir is None:
        cache_dir = PYTORCH_PRETRAINED_BERT_CACHE
    if isinstance(cache_dir, Path):
        cache_dir = str(cache_dir)

    cache_path = os.path.join(cache_dir, filename)
    if not os.path.exists(cache_path):
        raise FileNotFoundError("file {} not found".format(cache_path))

    meta_path = cache_path + '.json'
    if not os.path.exists(meta_path):
        raise FileNotFoundError("file {} not found".format(meta_path))

    with open(meta_path) as meta_file:
        metadata = json.load(meta_file)
    url = metadata['url']
    etag = metadata['etag']

    return url, etag 
开发者ID:ymcui,项目名称:cmrc2019,代码行数:26,代码来源:file_utils.py

示例4: encoding_detect

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Union [as 别名]
def encoding_detect(byte_content):
    """
    试图解析并返回二进制串的编码, 如果失败, 则返回 None
    :param byte_content: 待解码的二进制串
    :type byte_content: bytes
    :return: 编码类型或None
    :rtype: Union[str, None]
    """

    if force_decode_remote_using_encode is not None:
        return force_decode_remote_using_encode
    if possible_charsets:
        for charset in possible_charsets:
            try:
                byte_content.decode(encoding=charset)
            except:
                pass
            else:
                return charset
    if cchardet_available:  # detect the encoding using cchardet (if we have)
        return c_chardet(byte_content)['encoding']

    return None 
开发者ID:aploium,项目名称:zmirror,代码行数:25,代码来源:zmirror.py

示例5: try_get_cached_response

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Union [as 别名]
def try_get_cached_response(url, client_header=None):
    """
    尝试从本地缓存中取出响应
    :param url: real url with query string
    :type client_header: dict
    :rtype: Union[Response, None]
    """
    # Only use cache when client use GET
    if local_cache_enable and parse.method == 'GET' and cache.is_cached(url):
        if client_header is not None and 'if-modified-since' in client_header and \
                cache.is_unchanged(url, client_header.get('if-modified-since', None)):
            dbgprint('FileCacheHit-304', url)
            return generate_304_response()
        else:
            cached_info = cache.get_info(url)
            if cached_info.get('without_content', True):
                # 关于 without_content 的解释, 请看update_content_in_local_cache()函数
                return None
            # dbgprint('FileCacheHit-200')
            resp = cache.get_obj(url)
            assert isinstance(resp, Response)
            parse.set_extra_resp_header('x-zmirror-cache', 'FileHit')
            return resp
    else:
        return None 
开发者ID:aploium,项目名称:zmirror,代码行数:27,代码来源:zmirror.py

示例6: throttle

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Union [as 别名]
def throttle(interval: Union[float, int]):
    """Decorator ensures function that can only be called once every `s` seconds.
    """

    def decorate(fn: Callable) -> Callable:
        t = None

        def wrapped(*args, **kwargs):
            nonlocal t
            t_ = time()
            if t is None or t_ - t >= interval:
                result = fn(*args, **kwargs)
                t = time()
                return result

        return wrapped

    return decorate 
开发者ID:PhilipTrauner,项目名称:cmus-osx,代码行数:20,代码来源:util.py

示例7: _generic_gaussian_circuit

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Union [as 别名]
def _generic_gaussian_circuit(
        qubits: Sequence[cirq.Qid],
        quadratic_hamiltonian: QuadraticHamiltonian,
        occupied_orbitals: Optional[Sequence[int]],
        initial_state: Union[int, Sequence[int]]) -> cirq.OP_TREE:

    n_qubits = len(qubits)
    circuit_description, start_orbitals = gaussian_state_preparation_circuit(
            quadratic_hamiltonian, occupied_orbitals)

    if isinstance(initial_state, int):
        initially_occupied_orbitals = _occupied_orbitals(
                initial_state, n_qubits)
    else:
        initially_occupied_orbitals = initial_state  # type: ignore

    # Flip bits so that the correct starting orbitals are occupied
    yield (cirq.X(qubits[j]) for j in range(n_qubits)
           if (j in initially_occupied_orbitals) != (j in start_orbitals))

    yield _ops_from_givens_rotations_circuit_description(
            qubits, circuit_description) 
开发者ID:quantumlib,项目名称:OpenFermion-Cirq,代码行数:24,代码来源:state_preparation.py

示例8: get_status_summary

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Union [as 别名]
def get_status_summary(trial_results: List[MutantTrialResult]) -> Dict[str, Union[str, int]]:
    """Create a status summary dictionary for later formatting.

    Args:
        trial_results: list of mutant trials

    Returns:
        Dictionary with keys for formatting in the report
    """
    status: Dict[str, Union[str, int]] = dict(Counter([t.status for t in trial_results]))
    status["TOTAL RUNS"] = len(trial_results)
    status["RUN DATETIME"] = str(datetime.now())

    return status 
开发者ID:EvanKepner,项目名称:mutatest,代码行数:16,代码来源:report.py

示例9: __init__

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Union [as 别名]
def __init__(self, coverage_file: Union[str, Path] = Path(".coverage")) -> None:
        """Initialize the filter.

        Args:
            coverage_file: an optional coverage file, a default ".coverage" is used.
        """
        self._coverage_file = Path(coverage_file)
        self._coverage_data: Optional[CoverageData] = None 
开发者ID:EvanKepner,项目名称:mutatest,代码行数:10,代码来源:filters.py

示例10: coverage_file

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Union [as 别名]
def coverage_file(self, value: Union[str, Path]) -> None:
        """Setter for the coverage file, clears local cache of CoverageData.

        Args:
             value: The path to the coverage file

        Returns:
            None
        """
        self._coverage_file = Path(value)
        self._coverage_data = None 
开发者ID:EvanKepner,项目名称:mutatest,代码行数:13,代码来源:filters.py

示例11: filter

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Union [as 别名]
def filter(  # type: ignore
        self,
        loc_idxs: Set[LocIndex],
        source_file: Union[str, Path],
        invert: bool = False,
        resolve_source: bool = True,
    ) -> Set[LocIndex]:
        """Filter based on coverage measured file.

        This adds the source_file argument to the filter abstract method because the coverage
        file holds multiple measured-files, and the ``LocIndex`` object does not have a source
        file attribute. The choice is that the coverage file can be set and read once for the
        class instance, and any valid measured file can be used in the filter.

        Args:
            loc_idxs: location index set of targets
            source_file: source file that is measured by the coverage file
            invert: flag for inverted filter using NOT
            resolve_source: flag for using resolved source_file vs. direct str, default True.
                This exists mostly for testing purposes to access mocked entries in the
                fake coverage files.

        Returns:
            Filtered set of location index set
        """
        measured_file = str(Path(source_file).resolve()) if resolve_source else str(source_file)

        covered_lines = self.coverage_data.lines(measured_file) or list()

        if invert:
            return {loc for loc in loc_idxs if loc.lineno not in covered_lines}
        return {loc for loc in loc_idxs if loc.lineno in covered_lines} 
开发者ID:EvanKepner,项目名称:mutatest,代码行数:34,代码来源:filters.py

示例12: __init__

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Union [as 别名]
def __init__(
        self,
        target_idx: Optional[LocIndex] = None,
        mutation: Optional[Any] = None,
        readonly: bool = False,
        src_file: Optional[Union[Path, str]] = None,
    ) -> None:
        """Create the AST node transformer for mutations.

        If readonly is set to True then no transformations are applied;
        however, the locs attribute is updated with the locations of nodes that could
        be transformed. This allows the class to function both as an inspection method
        and as a mutation transformer.

        Note that different nodes handle the ``LocIndex`` differently based on the context. For
        example, ``visit_BinOp`` uses direct AST types, while ``visit_NameConstant`` uses values,
        and ``visit_AugAssign`` uses custom strings in a dictionary mapping.

        All ``visit_`` methods take the ``node`` as an argument and rely on the class properties.

        This MutateBase class is designed to be implemented with the appropriate Mixin Class
        for supporting either Python 3.7 or Python 3.8 ASTs. If the base class is used
        directly certain operations - like ``visit_If`` and ``visit_NameConstant`` will not
        work as intended..

        Args:
            target_idx: Location index for the mutatest in the AST
            mutation: the mutatest to apply, may be a type or a value
            readonly: flag for read-only operations, used to visit nodes instead of transform
            src_file: Source file name, used for logging purposes
        """
        self.locs: Set[LocIndex] = set()

        # managed via @property
        self._target_idx = target_idx
        self._mutation = mutation
        self._readonly = readonly
        self._src_file = src_file 
开发者ID:EvanKepner,项目名称:mutatest,代码行数:40,代码来源:transformers.py

示例13: constant_type

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Union [as 别名]
def constant_type(self) -> Union[Type[ast.NameConstant], Type[ast.Constant]]:
        """Overridden using the MixinClasses for NameConstant(3.7) vs. Constant(3.8)."""
        raise NotImplementedError 
开发者ID:EvanKepner,项目名称:mutatest,代码行数:5,代码来源:transformers.py

示例14: mixin_NameConstant

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Union [as 别名]
def mixin_NameConstant(self, node: Union[ast.NameConstant, ast.Constant]) -> ast.AST:
        """Constants: ``True, False, None``.

        This method is called by using the Mixin classes for handling the difference of
        ast.NameConstant (Py 3.7) an ast.Constant (Py 3.8).
        """
        self.generic_visit(node)
        log_header = f"visit_NameConstant: {self.src_file}:"

        node_span = NodeSpan(node)
        idx = LocIndex(
            ast_class="NameConstant",
            lineno=node_span.lineno,
            col_offset=node_span.col_offset,
            op_type=node.value,
            end_lineno=node_span.end_lineno,
            end_col_offset=node_span.end_col_offset,
        )
        self.locs.add(idx)

        if idx == self.target_idx and not self.readonly:
            LOGGER.debug("%s mutating idx: %s with %s", log_header, self.target_idx, self.mutation)
            return ast.copy_location(self.constant_type(value=self.mutation), node)

        LOGGER.debug("%s (%s, %s): no mutations applied.", log_header, node.lineno, node.col_offset)
        return node 
开发者ID:EvanKepner,项目名称:mutatest,代码行数:28,代码来源:transformers.py

示例15: get_cache_file_loc

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Union [as 别名]
def get_cache_file_loc(src_file: Union[str, Path]) -> Path:
    """Use importlib to determine the cache file location for the source file.

    Reference: https://github.com/python/cpython/blob/master/Lib/py_compile.py#L130

    Args:
        src_file: source file to determine cache file

    Returns:
        Path to the cache file

    Raises:
        FileExistsError: if the cache-file path is symlink or irregular file
    """
    if not src_file:
        raise ValueError("src_file cannot be an empty string.")

    cache_file = importlib.util.cache_from_source(str(src_file))  # type: ignore

    if os.path.islink(cache_file):
        msg = (
            "{} is a symlink and will be changed into a regular file if "
            "import writes a byte-compiled file to it"
        )
        raise FileExistsError(msg.format(cache_file))

    elif os.path.exists(cache_file) and not os.path.isfile(cache_file):
        msg = (
            "{} is a non-regular file and will be changed into a regular "
            "one if import writes a byte-compiled file to it"
        )
        raise FileExistsError(msg.format(cache_file))

    return Path(cache_file) 
开发者ID:EvanKepner,项目名称:mutatest,代码行数:36,代码来源:cache.py


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