本文整理汇总了Python中typing.Set方法的典型用法代码示例。如果您正苦于以下问题:Python typing.Set方法的具体用法?Python typing.Set怎么用?Python typing.Set使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类typing
的用法示例。
在下文中一共展示了typing.Set方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: import typing [as 别名]
# 或者: from typing import Set [as 别名]
def __init__(self, codes: Optional[Iterable[str]] = None):
"""Initialize the filter.
Args:
codes: An optional iterable of two-letter category codes for filtering.
Optional to set at initialization of the class, can be set through properties.
The codes property must be set prior to filtering.
Only codes that are valid categories are added, others are discarded.
Make sure you set appropriately as an iterable for single string values e.g.,
``codes=("bn",)``; otherwise, the codes property will set as empty.
"""
# managed by class properties, no direct setters
self._valid_categories = CATEGORIES # defined in transformers.py
self._codes: Set[str] = set()
# initialize through properties
self.codes = set(codes) if codes else set()
示例2: filter
# 需要导入模块: import typing [as 别名]
# 或者: from typing import Set [as 别名]
def filter(self, loc_idxs: Set[LocIndex], invert: bool = False) -> Set[LocIndex]:
"""Filter a set of location indices based on the set codes.
If the codes property is an empty set, the ``loc_idxs`` is returned unmodified.
Args:
loc_idxs: the set of location indices to filter.
invert: flag for inverted filtering using NOT
Returns:
Set of location indices with the filter applied.
"""
if not self.codes:
return loc_idxs
if invert:
return {loc for loc in loc_idxs if loc.op_type not in self.valid_mutations}
return {loc for loc in loc_idxs if loc.op_type in self.valid_mutations}
示例3: topologically_sorted_checks_with_deps
# 需要导入模块: import typing [as 别名]
# 或者: from typing import Set [as 别名]
def topologically_sorted_checks_with_deps(checks: Iterable[check.Check]
) -> List[check.Check]:
result = []
seen = set() # type: Set[check.Check]
def handle(item: check.Check):
if item in seen:
return
seen.add(item)
# Dependencies first.
for dep in item.dependencies:
handle(dep)
result.append(item)
for e in checks:
handle(e)
return result
示例4: determine_ignored_lines
# 需要导入模块: import typing [as 别名]
# 或者: from typing import Set [as 别名]
def determine_ignored_lines(content: str) -> Set[int]:
lines = content.split('\n')
result = [] # type: List[int]
i = 0
while i < len(lines):
# Drop spacing, including internal spacing within the comment.
joined_line = re.sub(r'\s+', '', lines[i])
if joined_line == EXPLICIT_OPT_OUT_COMMENT:
# Ignore the rest of a block.
end = naive_find_end_of_scope(lines, i)
result.extend(range(i, end))
i = end
elif joined_line.endswith(EXPLICIT_OPT_OUT_COMMENT):
# Ignore a single line.
result.append(i)
i += 1
else:
# Don't ignore.
i += 1
# Line numbers start at 1, not 0.
return {e + 1 for e in result}
示例5: _api_rst_fullnames_per_section
# 需要导入模块: import typing [as 别名]
# 或者: from typing import Set [as 别名]
def _api_rst_fullnames_per_section() -> List[List[str]]:
result: List[List[str]] = []
section: List[str] = []
seen: Set[str] = set()
with open(Path(__file__).parent / 'api.rst', mode='r') as f:
for line in f.readlines():
if line.strip() == '.. autosummary::':
if section:
result.append(section)
section = []
elif line.startswith(' openfermioncirq.'):
fullname = line.strip()
if fullname in seen:
# coverage: ignore
raise ValueError(f'{fullname} appears twice in api.rst')
section.append(fullname)
seen.add(fullname)
if section:
result.append(section)
return result
示例6: test_add_url_rule_methods
# 需要导入模块: import typing [as 别名]
# 或者: from typing import Set [as 别名]
def test_add_url_rule_methods(
methods: Set[str], required_methods: Set[str], automatic_options: bool
) -> None:
app = Quart(__name__)
def route() -> str:
return ""
route.methods = methods # type: ignore
route.required_methods = required_methods # type: ignore
non_func_methods = {"PATCH"} if not methods else None
app.add_url_rule(
"/", "end", route, methods=non_func_methods, provide_automatic_options=automatic_options
)
result = {"PATCH"} if not methods else set()
if automatic_options:
result.add("OPTIONS")
result.update(methods)
result.update(required_methods)
if "GET" in result:
result.add("HEAD")
assert app.url_map._rules_by_endpoint["end"][0].methods == result # type: ignore
示例7: test_add_url_rule_automatic_options
# 需要导入模块: import typing [as 别名]
# 或者: from typing import Set [as 别名]
def test_add_url_rule_automatic_options(
methods: Set[str],
arg_automatic: Optional[bool],
func_automatic: Optional[bool],
expected_methods: Set[str],
expected_automatic: bool,
) -> None:
app = Quart(__name__)
def route() -> str:
return ""
route.provide_automatic_options = func_automatic # type: ignore
app.add_url_rule("/", "end", route, methods=methods, provide_automatic_options=arg_automatic)
assert app.url_map._rules_by_endpoint["end"][0].methods == expected_methods # type: ignore
assert (
app.url_map._rules_by_endpoint["end"][0].provide_automatic_options # type: ignore
== expected_automatic
)
示例8: get_top_imported_names
# 需要导入模块: import typing [as 别名]
# 或者: from typing import Set [as 别名]
def get_top_imported_names(file: str) -> Set[str]:
"""Collect names imported in given file.
We only collect top-level names, i.e. `from foo.bar import baz`
will only add `foo` to the list.
"""
if not file.endswith(".pyi"):
return set()
with open(os.path.join(file), "rb") as f:
content = f.read()
parsed = ast.parse(content)
top_imported = set()
for node in ast.walk(parsed):
if isinstance(node, ast.Import):
for name in node.names:
top_imported.add(name.name.split('.')[0])
elif isinstance(node, ast.ImportFrom):
if node.level > 0:
# Relative imports always refer to the current package.
continue
assert node.module
top_imported.add(node.module.split('.')[0])
return top_imported
示例9: set_type_library
# 需要导入模块: import typing [as 别名]
# 或者: from typing import Set [as 别名]
def set_type_library(self, type_library: PushTypeLibrary):
"""Set the type library attribute and return self.
Parameters
----------
type_library
PushTypeLibrary to set.
Returns
-------
InstructionSet
A reference to the InstructionSet.
"""
self.type_library = type_library
return self
示例10: toDictWithStrValues
# 需要导入模块: import typing [as 别名]
# 或者: from typing import Set [as 别名]
def toDictWithStrValues(d):
if isNamedTuple(d):
return toDictWithStrValues(d._asdict())
if not isinstance(d, Dict):
return serializeToStr(d)
result = OrderedDict()
for key, value in d.items():
if isinstance(value, Dict):
result[serializeToStr(key)] = toDictWithStrValues(value)
elif isinstance(value, str):
result[serializeToStr(key)] = serializeToStr(value)
elif isNamedTuple(value):
result[serializeToStr(key)] = toDictWithStrValues(value._asdict())
elif isinstance(value, Set):
result[serializeToStr(key)] = {toDictWithStrValues(v) for v in
value}
elif isinstance(value, List):
result[serializeToStr(key)] = [toDictWithStrValues(v) for v in
value]
elif value:
result[serializeToStr(key)] = serializeToStr(value)
return result
示例11: fromDictWithStrValues
# 需要导入模块: import typing [as 别名]
# 或者: from typing import Set [as 别名]
def fromDictWithStrValues(d):
if not isinstance(d, Dict) and not isinstance(d, tuple):
return deserializeFromStr(d)
result = OrderedDict()
for key, value in d.items():
if isinstance(value, Dict):
result[deserializeFromStr(key)] = fromDictWithStrValues(value)
elif isinstance(value, str):
result[deserializeFromStr(key)] = deserializeFromStr(value)
elif isinstance(value, Set):
result[deserializeFromStr(key)] = {fromDictWithStrValues(v) for v in
value}
elif isinstance(value, List):
result[deserializeFromStr(key)] = [fromDictWithStrValues(v) for v in
value]
elif value:
result[deserializeFromStr(key)] = deserializeFromStr(value)
return result
示例12: apply_for_iteration
# 需要导入模块: import typing [as 别名]
# 或者: from typing import Set [as 别名]
def apply_for_iteration(self, solver, players_dict, result):
current_lineup = self.lineups[self.current_iteration]
unswappable_players = current_lineup.get_unswappable_players()
remaining_positions = get_remaining_positions(self.optimizer.settings.positions, unswappable_players)
# lock selected players
for player in unswappable_players:
solver.add_constraint([players_dict[player]], None, SolverSign.EQ, 1)
# set remaining positions
positions_combinations = set([tuple(sorted(player.positions)) for player in players_dict.keys()
if len(player.positions) > 1])
positions = get_positions_for_optimizer(remaining_positions, positions_combinations)
players_for_optimization = set()
for position, places in positions.items():
players_with_position = [variable for player, variable in players_dict.items()
if list_intersection(position, player.positions) and
player not in unswappable_players]
players_for_optimization.update(players_with_position)
solver.add_constraint(players_with_position, None, SolverSign.GTE, places)
# Set total players for optimization
solver.add_constraint(players_for_optimization, None, SolverSign.EQ, len(remaining_positions))
# Exclude players with active games
for player, variable in players_dict.items():
if player not in unswappable_players and player.is_game_started:
solver.add_constraint([players_dict[player]], None, SolverSign.EQ, 0)
self.current_iteration += 1
示例13: test_methods
# 需要导入模块: import typing [as 别名]
# 或者: from typing import Set [as 别名]
def test_methods(self, method, use_typing):
List, Dict = converters.typing_._get_types(use_typing)
# Verify with sequence
converter = method(List[str])
assert isinstance(converter, converters.typing_.ListConverter)
# Verify with mapping
converter = method(Dict[str, str])
assert isinstance(converter, converters.typing_.DictConverter)
# Verify with unsupported value
converter = method(None)
assert converter is None
# Verify with unsupported type
if use_typing:
converter = method(typing.Set[str])
assert converter is None
示例14: create
# 需要导入模块: import typing [as 别名]
# 或者: from typing import Set [as 别名]
def create(
server_info: ServerConnectivityInfo = ServerConnectivityInfoFactory.create(),
scan_commands_results: Optional[ScanCommandResultsDict] = None,
scan_commands_errors: Optional[ScanCommandErrorsDict] = None,
) -> ServerScanResult:
final_results: ScanCommandResultsDict = (
scan_commands_results
if scan_commands_results
else {ScanCommand.TLS_COMPRESSION: CompressionScanResult(supports_compression=True)}
)
final_errors: ScanCommandErrorsDict = scan_commands_errors if scan_commands_errors else {}
scan_commands: Set[ScanCommandType] = set()
for scan_cmd in final_results.keys():
typed_scan_cmd = cast(ScanCommandType, scan_cmd)
scan_commands.add(typed_scan_cmd)
for scan_cmd in final_errors.keys():
scan_commands.add(scan_cmd)
return ServerScanResult(
scan_commands_results=final_results,
scan_commands_errors=final_errors,
server_info=server_info,
scan_commands=scan_commands,
scan_commands_extra_arguments={},
)
示例15: update_text
# 需要导入模块: import typing [as 别名]
# 或者: from typing import Set [as 别名]
def update_text(self, matched: str, unmatched: str) -> None:
"""Set the text for the hint.
Args:
matched: The part of the text which was typed.
unmatched: The part of the text which was not typed yet.
"""
if (config.cache['hints.uppercase'] and
self._context.hint_mode in ['letter', 'word']):
matched = html.escape(matched.upper())
unmatched = html.escape(unmatched.upper())
else:
matched = html.escape(matched)
unmatched = html.escape(unmatched)
if matched:
match_color = config.cache['colors.hints.match.fg'].name()
self.setText('<font color="{}">{}</font>{}'.format(
match_color, matched, unmatched))
else:
self.setText(unmatched)
self.adjustSize()