本文整理汇总了Python中collections.abc.Set方法的典型用法代码示例。如果您正苦于以下问题:Python abc.Set方法的具体用法?Python abc.Set怎么用?Python abc.Set使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类collections.abc
的用法示例。
在下文中一共展示了abc.Set方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_basic_init_default_ctx
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Set [as 别名]
def test_basic_init_default_ctx(self):
ctx_resp = gb.init_sec_context(self.target_name)
ctx_resp.shouldnt_be_none()
(ctx, out_mech_type,
out_req_flags, out_token, out_ttl, cont_needed) = ctx_resp
ctx.shouldnt_be_none()
ctx.should_be_a(gb.SecurityContext)
out_mech_type.should_be(gb.MechType.kerberos)
out_req_flags.should_be_a(Set)
out_req_flags.should_be_at_least_length(2)
out_token.shouldnt_be_empty()
out_ttl.should_be_greater_than(0)
cont_needed.should_be_a(bool)
gb.delete_sec_context(ctx)
示例2: test_equality_Set
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Set [as 别名]
def test_equality_Set(self):
class MySet(Set):
def __init__(self, itr):
self.contents = itr
def __contains__(self, x):
return x in self.contents
def __iter__(self):
return iter(self.contents)
def __len__(self):
return len([x for x in self.contents])
s1 = MySet((1,))
s2 = MySet((1, 2))
s3 = MySet((3, 4))
s4 = MySet((3, 4))
self.assertTrue(s2 > s1)
self.assertTrue(s1 < s2)
self.assertFalse(s2 <= s1)
self.assertFalse(s2 <= s3)
self.assertFalse(s1 >= s2)
self.assertEqual(s3, s4)
self.assertNotEqual(s2, s3)
示例3: test_MutableMapping_subclass
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Set [as 别名]
def test_MutableMapping_subclass(self):
# Test issue 9214
mymap = UserDict()
mymap['red'] = 5
self.assertIsInstance(mymap.keys(), Set)
self.assertIsInstance(mymap.keys(), KeysView)
self.assertIsInstance(mymap.items(), Set)
self.assertIsInstance(mymap.items(), ItemsView)
mymap = UserDict()
mymap['red'] = 5
z = mymap.keys() | {'orange'}
self.assertIsInstance(z, set)
list(z)
mymap['blue'] = 7 # Shouldn't affect 'z'
self.assertEqual(sorted(z), ['orange', 'red'])
mymap = UserDict()
mymap['red'] = 5
z = mymap.items() | {('orange', 3)}
self.assertIsInstance(z, set)
list(z)
mymap['blue'] = 7 # Shouldn't affect 'z'
self.assertEqual(sorted(z), [('orange', 3), ('red', 5)])
示例4: NamedTuple
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Set [as 别名]
def NamedTuple(typename, fields):
"""Typed version of namedtuple.
Usage::
Employee = typing.NamedTuple('Employee', [('name', str), 'id', int)])
This is equivalent to::
Employee = collections.namedtuple('Employee', ['name', 'id'])
The resulting class has one extra attribute: _field_types,
giving a dict mapping field names to types. (The field names
are in the _fields attribute, which is part of the namedtuple
API.)
"""
fields = [(n, t) for n, t in fields]
cls = collections.namedtuple(typename, [n for n, t in fields])
cls._field_types = dict(fields)
# Set the module to the caller's module (otherwise it'd be 'typing').
try:
cls.__module__ = sys._getframe(1).f_globals.get('__name__', '__main__')
except (AttributeError, ValueError):
pass
return cls
示例5: detect_language
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Set [as 别名]
def detect_language(self, text, languages):
if isinstance(languages, (list, tuple, Set)):
if all([language in self.available_language_map for language in languages]):
languages = [self.available_language_map[language] for language in languages]
else:
unsupported_languages = set(languages) - set(self.available_language_map.keys())
raise ValueError(
"Unknown language(s): %s" % ', '.join(map(repr, unsupported_languages)))
elif languages is not None:
raise TypeError("languages argument must be a list (%r given)" % type(languages))
if languages:
self.language_detector = FullTextLanguageDetector(languages=languages)
else:
self.language_detector = FullTextLanguageDetector(list(self.available_language_map.values()))
return self.language_detector._best_language(text)
示例6: process_inline_members_definition
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Set [as 别名]
def process_inline_members_definition(members):
"""
:param members: this can be any of the following:
- a string containing a space and/or comma separated list of names: e.g.:
"item1 item2 item3" OR "item1,item2,item3" OR "item1, item2, item3"
- tuple/list/Set of strings (names)
- Mapping of (name, data) pairs
- any kind of iterable that yields (name, data) pairs
:return: An iterable of (name, data) pairs.
"""
if isinstance(members, str):
members = ((name, UNDEFINED) for name in members.replace(',', ' ').split())
elif isinstance(members, (tuple, list, Set)):
if members and isinstance(next(iter(members)), str):
members = ((name, UNDEFINED) for name in members)
elif isinstance(members, Mapping):
members = members.items()
return members
示例7: __init__
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Set [as 别名]
def __init__(self, viewer, nbunch=None, data=False, default=None):
self._viewer = viewer
self._adjdict = viewer._adjdict
if nbunch is None:
self._nodes_nbrs = self._adjdict.items
else:
nbunch = list(viewer._graph.nbunch_iter(nbunch))
self._nodes_nbrs = lambda: [(n, self._adjdict[n]) for n in nbunch]
self._nbunch = nbunch
self._data = data
self._default = default
# Set _report based on data and default
if data is True:
self._report = lambda n, nbr, dd: (n, nbr, dd)
elif data is False:
self._report = lambda n, nbr, dd: (n, nbr)
else: # data is attribute name
self._report = lambda n, nbr, dd: \
(n, nbr, dd[data]) if data in dd else (n, nbr, default)
示例8: set
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Set [as 别名]
def set(self, key, value):
'''A short cut to set value to key without triggering any logging
or warning message.'''
if hasattr(value, 'labels'):
if 'VARIABLE' in env.config['SOS_DEBUG'] or 'ALL' in env.config[
'SOS_DEBUG']:
env.log_to_file(
'VARIABLE',
f"Set {key} to {short_repr(value)} with labels {short_repr(value.labels)}"
)
else:
if 'VARIABLE' in env.config['SOS_DEBUG'] or 'ALL' in env.config[
'SOS_DEBUG']:
env.log_to_file(
'VARIABLE',
f"Set {key} to {short_repr(value)} of type {value.__class__.__name__}"
)
self._dict[key] = value
# if self._change_all_cap_vars is not None and key.isupper():
# self._check_readonly(key, value)
示例9: stable_repr
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Set [as 别名]
def stable_repr(obj):
if isinstance(obj, str):
return repr(obj)
if hasattr(obj, '__stable_repr__'):
return obj.__stable_repr__()
if isinstance(obj, Mapping):
items = [stable_repr(k) + ':' + stable_repr(obj[k]) for k in obj.keys()]
return '{' + ', '.join(sorted(items)) + '}'
if isinstance(obj, Set):
items = [stable_repr(x) for x in obj]
return '{' + ', '.join(sorted(items)) + '}'
if isinstance(obj, Sequence):
return '[' + ', '.join(stable_repr(k) for k in obj) + ']'
return repr(obj)
#
# A utility function that returns output of a command
示例10: __make_cmp
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Set [as 别名]
def __make_cmp(set_op, symbol, doc):
"Make comparator method."
def comparer(self, other):
"Compare method for sorted set and set."
if isinstance(other, SortedSet):
return set_op(self._set, other._set)
elif isinstance(other, Set):
return set_op(self._set, other)
return NotImplemented
set_op_name = set_op.__name__
comparer.__name__ = '__{0}__'.format(set_op_name)
doc_str = """Return true if and only if sorted set is {0} `other`.
``ss.__{1}__(other)`` <==> ``ss {2} other``
Comparisons use subset and superset semantics as with sets.
Runtime complexity: `O(n)`
:param other: `other` set
:return: true if sorted set is {0} `other`
"""
comparer.__doc__ = dedent(doc_str.format(doc, set_op_name, symbol))
return comparer
示例11: token_location
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Set [as 别名]
def token_location(self):
locations = current_app.config['JWT_TOKEN_LOCATION']
if isinstance(locations, str):
locations = (locations,)
elif not isinstance(locations, (Sequence, Set)):
raise RuntimeError('JWT_TOKEN_LOCATION must be a sequence or a set')
elif not locations:
raise RuntimeError('JWT_TOKEN_LOCATION must contain at least one '
'of "headers", "cookies", "query_string", or "json"')
for location in locations:
if location not in ('headers', 'cookies', 'query_string', 'json'):
raise RuntimeError('JWT_TOKEN_LOCATION can only contain '
'"headers", "cookies", "query_string", or "json"')
return locations
示例12: blacklist_checks
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Set [as 别名]
def blacklist_checks(self):
check_type = current_app.config['JWT_BLACKLIST_TOKEN_CHECKS']
if isinstance(check_type, str):
check_type = (check_type,)
elif not isinstance(check_type, (Sequence, Set)):
raise RuntimeError('JWT_BLACKLIST_TOKEN_CHECKS must be a sequence or a set')
for item in check_type:
if item not in ('access', 'refresh'):
err = 'JWT_BLACKLIST_TOKEN_CHECKS must be "access" or "refresh"'
raise RuntimeError(err)
return check_type
示例13: iter_serialize_variables
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Set [as 别名]
def iter_serialize_variables(variables):
# want to handle things like numpy numbers and fractions that do not
# serialize so easy
for v in variables:
if isinstance(v, Integral):
yield int(v)
elif isinstance(v, Number):
yield float(v)
elif isinstance(v, str):
yield v
# we want Collection, but that's not available in py3.5
elif isinstance(v, (abc.Sequence, abc.Set)):
yield tuple(iter_serialize_variables(v))
else:
yield v
示例14: iter_deserialize_variables
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Set [as 别名]
def iter_deserialize_variables(variables):
# convert list back into tuples
for v in variables:
# we want Collection, but that's not available in py3.5
if isinstance(v, (abc.Sequence, abc.Set)) and not isinstance(v, str):
yield tuple(iter_deserialize_variables(v))
else:
yield v
示例15: __eq__
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Set [as 别名]
def __eq__(self, other):
if isinstance(other, abc.Sequence):
return len(self) == len(other) and all(map(eq, self, other))
elif isinstance(other, abc.Set):
return not (self ^ other)
else:
return False