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


Python typing.AnyStr方法代码示例

本文整理汇总了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 
开发者ID:ipfs-shipyard,项目名称:py-ipfs-http-client,代码行数:23,代码来源:filescanner.py

示例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() 
开发者ID:ipfs-shipyard,项目名称:py-ipfs-http-client,代码行数:22,代码来源:multipart.py

示例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 
开发者ID:ipfs-shipyard,项目名称:py-ipfs-http-client,代码行数:22,代码来源:test_filescanner.py

示例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] 
开发者ID:Microvellum,项目名称:Fluid-Designer,代码行数:23,代码来源:test_typing.py

示例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]) 
开发者ID:Microvellum,项目名称:Fluid-Designer,代码行数:19,代码来源:test_typing.py

示例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 
开发者ID:demisto,项目名称:content,代码行数:25,代码来源:PhishLabsIOC_EIR.py

示例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 
开发者ID:allegroai,项目名称:trains-agent,代码行数:26,代码来源:base.py

示例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)
        ) 
开发者ID:ethereum,项目名称:eth-utils,代码行数:18,代码来源:address.py

示例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)) 
开发者ID:ethereum,项目名称:eth-utils,代码行数:22,代码来源:address.py

示例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) 
开发者ID:Paradoxis,项目名称:Flask-Unsign,代码行数:18,代码来源:session.py

示例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 
开发者ID:ctpbee,项目名称:ctpbee,代码行数:21,代码来源:helpers.py

示例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)) 
开发者ID:mrgambal,项目名称:vulyk,代码行数:27,代码来源:task_types.py

示例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)) 
开发者ID:pgjones,项目名称:quart,代码行数:4,代码来源:globals.py

示例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() 
开发者ID:pgjones,项目名称:quart,代码行数:5,代码来源:testing.py

示例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) 
开发者ID:pgjones,项目名称:quart,代码行数:5,代码来源:testing.py


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