本文整理匯總了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
示例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
示例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
示例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
示例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
示例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
示例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)
示例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
示例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
示例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
示例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}
示例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
示例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
示例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
示例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)