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