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


Python typing.Pattern方法代码示例

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


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

示例1: __init__

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Pattern [as 别名]
def __init__(self, backend, zoo_models, parent_module=None):
        # type: (Type[Backend], List[Dict[str,str]], Optional[str]) -> None
        self.backend = backend
        self._parent_module = parent_module
        self._include_patterns = set()  # type: Set[Pattern[Text]]
        self._exclude_patterns = set()  # type: Set[Pattern[Text]]
        self._test_items = defaultdict(dict)  # type: Dict[Text, Dict[Text, TestItem]]

        for zoo_model in zoo_models:
            test_name = 'test_{}'.format(zoo_model['model_name'])

            test_case = OnnxTestCase(
                name=test_name,
                url=zoo_model['url'],
                model_name=zoo_model['model_name'],
                model_dir=None,
                model=None,
                data_sets=None,
                kind='OnnxBackendRealModelTest',
                rtol=zoo_model.get('rtol', 0.001),
                atol=zoo_model.get('atol', 1e-07),
            )
            self._add_model_test(test_case, 'Zoo') 
开发者ID:NervanaSystems,项目名称:ngraph-onnx,代码行数:25,代码来源:model_zoo_tester.py

示例2: get_addon_version

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Pattern [as 别名]
def get_addon_version(
        self, addon: Addon, addon_path: str, version_file_regexp: Pattern[str], to_strip: str
    ) -> str:
        version = ""
        try:
            path = os.path.join(addon_path, addon.filename)
            with open(path, encoding="utf8") as addon_info:
                for line in addon_info:
                    version = version_file_regexp.search(line)
                    if version:
                        candidate_version = str(version.group(1).strip(to_strip))
                        if candidate_version != "VERSION": # Drupal specific
                            addon.version = candidate_version
                            LOGGER.print_cms("default", "Version : " + addon.version, "", 1)
                            break

        except FileNotFoundError as e:
            msg = "No standard extension file. Search manually !"
            LOGGER.print_cms("alert", "[-] " + msg, "", 1)
            addon.notes = msg
            return ""
        return addon.version 
开发者ID:Intrinsec,项目名称:comission,代码行数:24,代码来源:GenericCMS.py

示例3: extract_code_example

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Pattern [as 别名]
def extract_code_example(source: List[str], snippet: List[Any],
                         example_regex: Pattern[str]) -> List[Any]:
    start = -1
    end = -1
    for line in source:
        match = example_regex.search(line)
        if match:
            if match.group(1) == 'start':
                start = source.index(line)
            elif match.group(1) == 'end':
                end = source.index(line)
                break

    if (start == -1 and end == -1):
        return snippet

    snippet.append(source[start + 1: end])
    source = source[end + 1:]
    return extract_code_example(source, snippet, example_regex) 
开发者ID:zulip,项目名称:zulip,代码行数:21,代码来源:markdown_extension.py

示例4: __init__

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Pattern [as 别名]
def __init__(
        self,
        expected_warning: Optional[
            Union["Type[Warning]", Tuple["Type[Warning]", ...]]
        ] = None,
        match_expr: Optional[Union[str, "Pattern"]] = None,
    ) -> None:
        super().__init__()

        msg = "exceptions must be derived from Warning, not %s"
        if expected_warning is None:
            expected_warning_tup = None
        elif isinstance(expected_warning, tuple):
            for exc in expected_warning:
                if not issubclass(exc, Warning):
                    raise TypeError(msg % type(exc))
            expected_warning_tup = expected_warning
        elif issubclass(expected_warning, Warning):
            expected_warning_tup = (expected_warning,)
        else:
            raise TypeError(msg % type(expected_warning))

        self.expected_warning = expected_warning_tup
        self.match_expr = match_expr 
开发者ID:pytest-dev,项目名称:pytest,代码行数:26,代码来源:recwarn.py

示例5: _compareTimeStep

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Pattern [as 别名]
def _compareTimeStep(
    out, refGroup, srcGroup, diffResults, exclusions: Optional[Sequence[Pattern]] = None
):
    groupNames, structDiffs = _compareH5Groups(
        out, refGroup, srcGroup, "composite objects/auxiliary data"
    )
    diffResults.addStructureDiffs(structDiffs)

    componentTypes = {gn for gn in groupNames if gn in ArmiObject.TYPES}
    auxData = set(groupNames) - componentTypes
    auxData.discard("layout")

    for componentType in componentTypes:
        refTypeGroup = refGroup[componentType]
        srcTypeGroup = srcGroup[componentType]

        _compareComponentData(
            out, refTypeGroup, srcTypeGroup, diffResults, exclusions=exclusions
        )

    for aux in auxData:
        _compareAuxData(out, refGroup[aux], srcGroup[aux], diffResults, exclusions) 
开发者ID:terrapower,项目名称:armi,代码行数:24,代码来源:compareDB3.py

示例6: test_any_is_subclass

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Pattern [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

示例7: test_basics

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Pattern [as 别名]
def test_basics(self):
        pat = re.compile('[a-z]+', re.I)
        assert issubclass(pat.__class__, Pattern)
        assert issubclass(type(pat), Pattern)
        assert issubclass(type(pat), Pattern[str])

        mat = pat.search('12345abcde.....')
        assert issubclass(mat.__class__, Match)
        assert issubclass(mat.__class__, Match[str])
        assert issubclass(mat.__class__, Match[bytes])  # Sad but true.
        assert issubclass(type(mat), Match)
        assert issubclass(type(mat), Match[str])

        p = Pattern[Union[str, bytes]]
        assert issubclass(Pattern[str], Pattern)
        assert issubclass(Pattern[str], p)

        m = Match[Union[bytes, str]]
        assert issubclass(Match[bytes], Match)
        assert issubclass(Match[bytes], m) 
开发者ID:Microvellum,项目名称:Fluid-Designer,代码行数:22,代码来源:test_typing.py

示例8: test_errors

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Pattern [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

示例9: _filenames

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Pattern [as 别名]
def _filenames(
        files_re: Pattern[str],
        exclude_re: Pattern[str],
        tests_re: Pattern[str],
) -> Generator[Tuple[str, bool], None, None]:
    # TODO: zsplit is more correct than splitlines
    out = subprocess.check_output(('git', 'ls-files')).decode()
    for filename in out.splitlines():
        if (
                not files_re.search(filename) or
                exclude_re.search(filename) or
                not os.path.exists(filename) or
                'python' not in tags_from_path(filename)
        ):
            continue

        yield filename, bool(tests_re.search(filename)) 
开发者ID:asottile,项目名称:dead,代码行数:19,代码来源:dead.py

示例10: get_first_match

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Pattern [as 别名]
def get_first_match(pattern: Pattern, string: str) -> str:
    """Return the first matching substring.

    Args:
        pattern: The pattern to find.
        string: The string to search.

    Returns:
        The first occurence of the pattern in the string.

    Raises:
        ValueError if the string does not match the pattern.
    """
    match = pattern.match(string)
    if match is None:
        raise ValueError("String '{}' does not match the pattern '{}'"
                         .format(string, pattern.pattern))
    return match.group(1)


# this is a function because of the parse_*
# functions which are not defined yet 
开发者ID:ufal,项目名称:neuralmonkey,代码行数:24,代码来源:parsing.py

示例11: marker_from_regex

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Pattern [as 别名]
def marker_from_regex(expression: Union[str, Pattern], color: int, flags: int = re.UNICODE) -> MarkerFunc:
    color = max(1, min(color, 3))
    if isinstance(expression, str):
        pat = re.compile(expression, flags=flags)
    else:
        pat = expression

    def marker(text: str, left_address: int, right_address: int, color_address: int) -> Generator[None, None, None]:
        left, right, colorv = get_output_variables(left_address, right_address, color_address)
        colorv.value = color
        for match in pat.finditer(text):
            left.value = match.start()
            right.value = match.end() - 1
            yield

    return marker 
开发者ID:kovidgoyal,项目名称:kitty,代码行数:18,代码来源:marks.py

示例12: find_app_id

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Pattern [as 别名]
def find_app_id(tar: Any, app_folder_regex: Pattern) -> str:
    """
    Finds and returns the app id by looking at the first level folder
    :raises InvalidAppPackageStructureException: if there is no valid or
     to many app folders
    :param tar: the archive
    :return: the app id
    """
    folders = find_app_folders(tar, app_folder_regex)
    if len(folders) > 1:
        msg = 'More than one possible app folder found'
        raise InvalidAppPackageStructureException(msg)
    elif len(folders) == 0:
        msg = 'No possible app folder found. App folder must contain ' \
              'only lowercase ASCII characters or underscores'
        raise InvalidAppPackageStructureException(msg)
    return folders.pop() 
开发者ID:nextcloud,项目名称:appstore,代码行数:19,代码来源:parser.py

示例13: __init__

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Pattern [as 别名]
def __init__(
        self,
        builddir: Builddir,
        build_args: str,
        no_shell: bool,
        api_token: Optional[str] = None,
        use_ofborg_eval: Optional[bool] = True,
        only_packages: Set[str] = set(),
        package_regexes: List[Pattern[str]] = [],
        checkout: CheckoutOption = CheckoutOption.MERGE,
    ) -> None:
        self.builddir = builddir
        self.build_args = build_args
        self.no_shell = no_shell
        self.github_client = GithubClient(api_token)
        self.use_ofborg_eval = use_ofborg_eval
        self.checkout = checkout
        self.only_packages = only_packages
        self.package_regex = package_regexes 
开发者ID:Mic92,项目名称:nixpkgs-review,代码行数:21,代码来源:review.py

示例14: filter_packages

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Pattern [as 别名]
def filter_packages(
    changed_packages: Set[str],
    specified_packages: Set[str],
    package_regexes: List[Pattern[str]],
) -> Set[str]:
    packages: Set[str] = set()

    if len(specified_packages) == 0 and len(package_regexes) == 0:
        return changed_packages

    if len(specified_packages) > 0:
        packages = join_packages(changed_packages, specified_packages)

    for attr in changed_packages:
        for regex in package_regexes:
            if regex.match(attr):
                packages.add(attr)
    return packages 
开发者ID:Mic92,项目名称:nixpkgs-review,代码行数:20,代码来源:review.py

示例15: _compile_regex

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Pattern [as 别名]
def _compile_regex(self, pattern: str) -> typing.Pattern[str]:
        """Check if the given regex is valid.

        This is more complicated than it could be since there's a warning on
        invalid escapes with newer Python versions, and we want to catch that
        case and treat it as invalid.
        """
        with warnings.catch_warnings(record=True) as recorded_warnings:
            warnings.simplefilter('always')
            try:
                compiled = re.compile(pattern, self.flags)
            except re.error as e:
                raise configexc.ValidationError(
                    pattern, "must be a valid regex - " + str(e))
            except RuntimeError:  # pragma: no cover
                raise configexc.ValidationError(
                    pattern, "must be a valid regex - recursion depth "
                    "exceeded")

        assert recorded_warnings is not None

        for w in recorded_warnings:
            if (issubclass(w.category, DeprecationWarning) and
                    str(w.message).startswith('bad escape')):
                raise configexc.ValidationError(
                    pattern, "must be a valid regex - " + str(w.message))
            warnings.warn(w.message)

        return compiled 
开发者ID:qutebrowser,项目名称:qutebrowser,代码行数:31,代码来源:configtypes.py


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