本文整理匯總了Python中typing.AnyStr方法的典型用法代碼示例。如果您正苦於以下問題:Python typing.AnyStr方法的具體用法?Python typing.AnyStr怎麽用?Python typing.AnyStr使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類typing
的用法示例。
在下文中一共展示了typing.AnyStr方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: matcher_from_spec
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import AnyStr [as 別名]
def matcher_from_spec(spec: match_spec_t[ty.AnyStr], *,
period_special: bool = True,
recursive: bool = True) -> Matcher[ty.AnyStr]:
"""Processes the given simplified matching spec, creating an equivalent :type:`Matcher` object"""
if not recursive:
return NoRecusionAdapterMatcher(
matcher_from_spec(spec, recursive=True, period_special=period_special)
)
if spec is None:
return DUMMY_MATCHER
elif isinstance(spec, (str, bytes)):
return GlobMatcher(spec, period_special=period_special)
elif isinstance(spec, re_pattern_t):
return ReMatcher(spec)
elif isinstance(spec, collections.abc.Iterable) and not isinstance(spec, Matcher):
return MetaMatcher(
[matcher_from_spec(s, recursive=recursive, period_special=period_special) for s in spec]
)
else:
return spec
示例2: stream_directory
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import AnyStr [as 別名]
def stream_directory(directory: ty.Union[utils.path_t, int], *,
chunk_size: int = default_chunk_size,
follow_symlinks: bool = False,
patterns: match_spec_t[ty.AnyStr] = None,
period_special: bool = True,
recursive: bool = False):
"""Returns buffered generator yielding the contents of a directory
Returns a buffered generator which encodes a directory as
:mimetype:`multipart/form-data` with the corresponding headers.
For the meaning of these parameters see the description of
:class:`DirectoryStream`.
"""
stream = DirectoryStream(directory, chunk_size=chunk_size,
follow_symlinks=follow_symlinks,
period_special=period_special,
patterns=patterns, recursive=recursive)
return stream.body(), stream.headers()
示例3: test_glob_matching
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import AnyStr [as 別名]
def test_glob_matching(
monkeypatch,
pattern: ty.Union[ty.AnyStr, filescanner.re_pattern_t, ty.List[ty.Union[ty.AnyStr, filescanner.re_pattern_t]]],
path: ty.AnyStr,
is_dir: bool,
descend: bool,
report: bool,
kwargs: ty.Dict[str, bool]
):
# Hopefully useless sanity check
assert os.path.sep == "/" or os.path.altsep == "/"
slash = "/" if isinstance(path, str) else b"/" # type: ty.AnyStr
sep = os.path.sep if isinstance(path, str) else os.fsencode(os.path.sep) # type: ty.AnyStr
path = path.replace(slash, sep)
matcher = filescanner.matcher_from_spec(pattern, **kwargs)
assert matcher.should_descend(path) is descend
assert matcher.should_report(path, is_dir=is_dir) is report
示例4: test_any_is_subclass
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import AnyStr [as 別名]
def test_any_is_subclass(self):
# Any should be considered a subclass of everything.
assert issubclass(Any, Any)
assert issubclass(Any, typing.List)
assert issubclass(Any, typing.List[int])
assert issubclass(Any, typing.List[T])
assert issubclass(Any, typing.Mapping)
assert issubclass(Any, typing.Mapping[str, int])
assert issubclass(Any, typing.Mapping[KT, VT])
assert issubclass(Any, Generic)
assert issubclass(Any, Generic[T])
assert issubclass(Any, Generic[KT, VT])
assert issubclass(Any, AnyStr)
assert issubclass(Any, Union)
assert issubclass(Any, Union[int, str])
assert issubclass(Any, typing.Match)
assert issubclass(Any, typing.Match[str])
# These expressions must simply not fail.
typing.Match[Any]
typing.Pattern[Any]
typing.IO[Any]
示例5: test_errors
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import AnyStr [as 別名]
def test_errors(self):
with self.assertRaises(TypeError):
# Doesn't fit AnyStr.
Pattern[int]
with self.assertRaises(TypeError):
# Can't change type vars?
Match[T]
m = Match[Union[str, bytes]]
with self.assertRaises(TypeError):
# Too complicated?
m[str]
with self.assertRaises(TypeError):
# We don't support isinstance().
isinstance(42, Pattern)
with self.assertRaises(TypeError):
# We don't support isinstance().
isinstance(42, Pattern[str])
示例6: indicators_to_list_ec
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import AnyStr [as 別名]
def indicators_to_list_ec(indicators: List, type_ec: AnyStr) -> Union[Tuple[List, List], List]:
"""Unpack list of indicators to demisto ec format
Convert list of indicators from raw response to demisto entry context format lists
Args:
indicators: lit of indicators from raw response
type_ec: type of indicators
Returns:
List of indicators entry context and if not integration context also dbotscore
"""
dbots: List = []
ecs: List = []
if type_ec in ['url-ec', 'file-ec']:
for indicator in indicators:
dbotscore, ec = indicator_dbot_ec(indicator, type_ec)
ecs.append(ec)
dbots.append(dbotscore)
return ecs, dbots
else:
for indicator in indicators:
ec = indicator_ec(indicator, type_ec)
ecs.append(ec)
return ecs
示例7: mkstemp
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import AnyStr [as 別名]
def mkstemp(
open_kwargs=None, # type: Optional[Dict[Text, Any]]
text=True, # type: bool
name_only=False, # type: bool
*args,
**kwargs):
# type: (...) -> Union[(IO[AnyStr], Text), Text]
"""
WARNING: the returned file object is strict about its input type,
make sure to feed it binary/text input in correspondence to the ``text`` argument
:param open_kwargs: keyword arguments for ``io.open``
:param text: open in text mode
:param name_only: close the file and return its name
:param args: tempfile.mkstemp args
:param kwargs: tempfile.mkstemp kwargs
"""
fd, name = tempfile.mkstemp(text=text, *args, **kwargs)
mode = 'w+'
if not text:
mode += 'b'
if name_only:
os.close(fd)
return name
return io.open(fd, mode, **open_kwargs or {}), name
示例8: to_normalized_address
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import AnyStr [as 別名]
def to_normalized_address(value: AnyStr) -> HexAddress:
"""
Converts an address to its normalized hexadecimal representation.
"""
try:
hex_address = hexstr_if_str(to_hex, value).lower()
except AttributeError:
raise TypeError(
"Value must be any string, instead got type {}".format(type(value))
)
if is_address(hex_address):
return HexAddress(HexStr(hex_address))
else:
raise ValueError(
"Unknown format {}, attempted to normalize to {}".format(value, hex_address)
)
示例9: to_checksum_address
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import AnyStr [as 別名]
def to_checksum_address(value: AnyStr) -> ChecksumAddress:
"""
Makes a checksum address given a supported format.
"""
norm_address = to_normalized_address(value)
address_hash = encode_hex(keccak(text=remove_0x_prefix(HexStr(norm_address))))
checksum_address = add_0x_prefix(
HexStr(
"".join(
(
norm_address[i].upper()
if int(address_hash[i], 16) > 7
else norm_address[i]
)
for i in range(2, 42)
)
)
)
return ChecksumAddress(HexAddress(checksum_address))
示例10: sign
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import AnyStr [as 別名]
def sign(value: dict, secret: AnyStr, legacy: bool = False, salt: str = DEFAULT_SALT) -> str:
"""
Signs a custom session value with a known secret
:param value: Raw Python object (generally a dictionary) to serialize
:param secret: Server secret key
:param salt: Salt (default: 'cookie-session')
:param legacy: Should the legacy timestamp generator be used?
:return: Encoded string
"""
if not isinstance(secret, (bytes, str)):
raise SigningError(
f"Secret must be a string-type (bytes, str) and received "
f"{type(secret).__name__!r}. To fix this, either add quotes to the "
f"secret {secret!r} or use the --no-literal-eval argument.")
return get_serializer(secret, legacy, salt).dumps(value)
示例11: check
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import AnyStr [as 別名]
def check(type: AnyStr):
""" 檢查接口是否存在 """
def midlle(func):
@wraps(func)
def wrapper(*args, **kwargs):
if type == "market":
if args[0].app.market is None:
raise ValueError("當前賬戶行情api未連接,請檢查你的代碼中是否使用了行情接口API")
elif type == "trader":
if args[0].app.market is None:
raise ValueError("當前賬戶交易api未連接,請檢查你的代碼中是否使用了交易接口API")
else:
raise ValueError("非法字符串")
return func(*args, **kwargs)
return wrapper
return midlle
示例12: skip_task
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import AnyStr [as 別名]
def skip_task(self, task_id: AnyStr, user: User):
"""
Marks given task as a skipped by a given user
Assumes that user is eligible for this kind of tasks
:param task_id: Given task ID
:type task_id: AnyStr
:param user: an instance of User model who provided an answer
:type user: User
:raises: TaskSkipError, TaskNotFoundError
"""
try:
task = self.task_model.objects.get(
id=task_id,
task_type=self.type_name)
task.update(add_to_set__users_skipped=user)
self._work_session_manager.delete_work_session(task, user.id)
self._logger.debug('User %s skipped the task %s', user.id, task_id)
except self.task_model.DoesNotExist:
raise TaskNotFoundError()
except OperationError as err:
raise TaskSkipError('Can not skip the task: {0}.'.format(err))
示例13: get_data
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import AnyStr [as 別名]
def get_data(self, *args: Any, **kwargs: Any) -> AnyStr:
return sync_with_context(self._get_current_object().get_data(*args, **kwargs))
示例14: receive
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import AnyStr [as 別名]
def receive(self) -> AnyStr:
await self._check_for_response()
return await self.local_queue.get()
示例15: send
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import AnyStr [as 別名]
def send(self, data: AnyStr) -> None:
await self._check_for_response()
await self.remote_queue.put(data)