我们从Python开源项目中,提取了以下43个代码示例,用于说明如何使用collections.abc.Set()。
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)])
def __init__(self, member, flags=None): if flags is not None: assert (issubclass(type(flags), colabc.Set) or \ issubclass(type(flags), colabc.Sequence)) and \ not isinstance(flags, str), \ "flags must be a container and not a string" assert all([isinstance(flag, str) for flag in list(flags)]), \ "all flags must be strings, given{}".format(flags) super().__init__() self.member = member # list of selections self._registry = [] # list of flags for specific kinds of selections self._flags = set() if flags: self._flags.update(flags)
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
def frozen(struct): """Return an immutable, hashable version of the given data structure. Iterators (including generators) are hashable but mutable, so they are evaluated and returned as tuples---if they are infinite, this function will not exit. """ if isinstance(struct, Mapping): return frozenset((k, frozen(v)) for k, v in struct.items()) if isinstance(struct, Set): return frozenset(frozen(item) for item in struct) if isinstance(struct, Iterable): # Includes iterators and generators return tuple(frozen(item) for item in struct) hash(struct) # Raise TypeError for unhashable objects return struct
def hashified(struct, use_none=False): """Return a hashable version of the given data structure. If use_none is True, returns None instead of raising TypeError for unhashable types: this will serve as a bad but sometimes passable hash. See also functools._make_key, which might be a better choice. """ try: hash(struct) except TypeError: pass else: # Return the original object if it's already hashable return struct if isinstance(struct, Mapping): return frozenset((k, hashified(v)) for k, v in struct.items()) if isinstance(struct, Set): return frozenset(hashified(item) for item in struct) if isinstance(struct, Iterable): return tuple(hashified(item) for item in struct) if use_none: return None raise TypeError('unhashable type: {.__name__!r}'.format(type(struct)))
def _is_set(obj): return isinstance(obj, Set) and all(map(_is_value, obj))
def _is_list(obj): return (isinstance(obj, Sized) and isinstance(obj, Iterable) and not isinstance(obj, (Set, Mapping)))
def recalculate_prices(self): """Set new prices for all the commodities in the market""" for commodity in self.commodities: self._calculate_price(commodity)
def machine(): """ Return machine suffix to use in directory name when looking for bootloader. PyInstaller is reported to work even on ARM architecture. For that case functions system() and architecture() are not enough. Path to bootloader has to be composed from system(), architecture() and machine() like: 'Linux-32bit-arm' """ mach = platform.machine() if mach.startswith('arm'): return 'arm' else: # Assume x86/x86_64 machine. return None # Set and get environment variables does not handle unicode strings correctly # on Windows. # Acting on os.environ instead of using getenv()/setenv()/unsetenv(), # as suggested in <http://docs.python.org/library/os.html#os.environ>: # "Calling putenv() directly does not change os.environ, so it's # better to modify os.environ." (Same for unsetenv.)
def _file_is_filtered(self, tfile): if self._ffilter is None: return False # No filter specified elif isinstance(self._ffilter, (abc.Sequence, abc.Set)): # ffilter is a collection of file IDs return not tfile['id'] in self._ffilter else: # ffilter is a TorrentFileFilter instance return not self._ffilter.match(tfile)
def focused_file_ids(self): """File IDs of the focused files in a tuple""" focused = self.focused_widget if focused is not None: # The focused widget in the list can be a file or a directory. If # it's a directory, the 'file_id' property returns the IDs of all # the contained files recursively. fid = focused.file_id return tuple(fid) if isinstance(fid, (abc.Sequence, abc.Set)) else (fid,)
def test_Set(self): for sample in [set, frozenset]: self.assertIsInstance(sample(), Set) self.assertTrue(issubclass(sample, Set)) self.validate_abstract_methods(Set, '__contains__', '__iter__', '__len__') class MySet(Set): def __contains__(self, x): return False def __len__(self): return 0 def __iter__(self): return iter([]) self.validate_comparison(MySet())
def test_hash_Set(self): class OneTwoThreeSet(Set): def __init__(self): self.contents = [1, 2, 3] def __contains__(self, x): return x in self.contents def __len__(self): return len(self.contents) def __iter__(self): return iter(self.contents) def __hash__(self): return self._hash() a, b = OneTwoThreeSet(), OneTwoThreeSet() self.assertTrue(hash(a) == hash(b))
def test_issue16373(self): # Recursion error comparing comparable and noncomparable # Set instances class MyComparableSet(Set): def __contains__(self, x): return False def __len__(self): return 0 def __iter__(self): return iter([]) class MyNonComparableSet(Set): def __contains__(self, x): return False def __len__(self): return 0 def __iter__(self): return iter([]) def __le__(self, x): return NotImplemented def __lt__(self, x): return NotImplemented cs = MyComparableSet() ncs = MyNonComparableSet() with self.assertRaises(TypeError): ncs < cs with self.assertRaises(TypeError): ncs <= cs with self.assertRaises(TypeError): cs > ncs with self.assertRaises(TypeError): cs >= ncs
def __new__(cls, *args, **kwds): if _geqv(cls, Set): raise TypeError("Type Set cannot be instantiated; " "use set() instead") return set.__new__(cls, *args, **kwds)
def __subclasscheck__(self, cls): if issubclass(cls, Set): return False return super().__subclasscheck__(cls)
def test_issue16373(self): # Recursion error comparing comparable and noncomparable # Set instances class MyComparableSet(Set): def __contains__(self, x): return False def __len__(self): return 0 def __iter__(self): return iter([]) class MyNonComparableSet(Set): def __contains__(self, x): return False def __len__(self): return 0 def __iter__(self): return iter([]) def __le__(self, x): return NotImplemented def __lt__(self, x): return NotImplemented cs = MyComparableSet() ncs = MyNonComparableSet() self.assertFalse(ncs < cs) self.assertTrue(ncs <= cs) self.assertFalse(ncs > cs) self.assertTrue(ncs >= cs)
def __sub__(self, other): if isinstance(other, (BaseMultiset, set, frozenset)): pass elif not isinstance(other, Set): return NotImplemented return self.difference(other)
def __or__(self, other): if isinstance(other, (BaseMultiset, set, frozenset)): pass elif not isinstance(other, Set): return NotImplemented return self.union(other)
def __add__(self, other): if isinstance(other, (BaseMultiset, set, frozenset)): pass elif not isinstance(other, Set): return NotImplemented return self.combine(other)
def __and__(self, other): if isinstance(other, (BaseMultiset, set, frozenset)): pass elif not isinstance(other, Set): return NotImplemented return self.intersection(other)
def __xor__(self, other): if isinstance(other, (BaseMultiset, set, frozenset)): pass elif not isinstance(other, Set): return NotImplemented return self.symmetric_difference(other)
def __lt__(self, other): if isinstance(other, (BaseMultiset, set, frozenset)): pass elif not isinstance(other, Set): return NotImplemented return self._issubset(other, True)
def __ge__(self, other): if isinstance(other, (BaseMultiset, set, frozenset)): pass elif not isinstance(other, Set): return NotImplemented return self._issuperset(other, False)
def __gt__(self, other): if isinstance(other, (BaseMultiset, set, frozenset)): pass elif not isinstance(other, Set): return NotImplemented return self._issuperset(other, True)
def __eq__(self, other): if isinstance(other, BaseMultiset): return self._total == other._total and self._elements == other._elements if isinstance(other, (set, frozenset)): pass elif not isinstance(other, Set): return NotImplemented if self._total != len(other): return False return self._issubset(other, False)
def __ne__(self, other): if isinstance(other, BaseMultiset): return self._total != other._total or self._elements != other._elements if isinstance(other, (set, frozenset)): pass elif not isinstance(other, Set): return NotImplemented if self._total != len(other): return True return not self._issubset(other, False)
def __ior__(self, other): if isinstance(other, (BaseMultiset, set, frozenset)): pass elif not isinstance(other, Set): return NotImplemented self.union_update(other) return self
def __iand__(self, other): if isinstance(other, (BaseMultiset, set, frozenset)): pass elif not isinstance(other, Set): return NotImplemented self.intersection_update(other) return self
def __isub__(self, other): if isinstance(other, (BaseMultiset, set, frozenset)): pass elif not isinstance(other, Set): return NotImplemented self.difference_update(other) return self
def __ixor__(self, other): if isinstance(other, (BaseMultiset, set, frozenset)): pass elif not isinstance(other, Set): return NotImplemented self.symmetric_difference_update(other) return self
def __instancecheck__(self, obj): if issubclass(obj.__class__, Set): return False return super().__instancecheck__(obj)
def repository(): @singledispatch def _repogitory(obj): return obj def _register(cls, func=None): if func is None: return lambda f: _register(cls, f) if isinstance(func, type): if issubclass(func, ObjConverter): func = func(cls) if isinstance(func, ObjConverter): func.repogitory = _repogitory func = func.run return _repogitory.org_register(cls, func) _repogitory.org_register = _repogitory.register _repogitory.register = _register def fromSQLAlchemyModel(model, attrs=None, ignores=None): names = [col.name for col in model.__table__.columns] ObjConverter.build(_repogitory, model, names, attrs, ignores) _repogitory.fromSQLAlchemyModel = fromSQLAlchemyModel def fromDjangoModel(model, attrs, ignores): ObjConverter.build(_repogitory, model, _django_get_all_field_names(model), attrs, ignores) _repogitory.fromDjangoModel = fromDjangoModel def raw(obj): return obj _repogitory.register(str, raw) def conv_seq(obj): return tuple(_repogitory(o) for o in obj) _repogitory.register(abc.Sequence, conv_seq) _repogitory.register(abc.Set, conv_seq) @_repogitory.register(abc.Mapping) def conv_mapping(obj): return {_repogitory(k):_repogitory(v) for k, v in obj.items()} def conv_date(obj): return obj.isoformat() _repogitory.register(datetime.date, conv_date) _repogitory.register(datetime.datetime, conv_date) return _repogitory