Python collections.abc 模块,Set() 实例源码

我们从Python开源项目中,提取了以下43个代码示例,用于说明如何使用collections.abc.Set()

项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
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)])
项目:mastic    作者:ADicksonLab    | 项目源码 | 文件源码
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)
项目:sublimeTextConfig    作者:luoye-fe    | 项目源码 | 文件源码
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
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
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)])
项目:kbe_server    作者:xiaohaoppy    | 项目源码 | 文件源码
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)])
项目:phredutils    作者:doctaphred    | 项目源码 | 文件源码
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
项目:phredutils    作者:doctaphred    | 项目源码 | 文件源码
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)))
项目:pymzn    作者:paolodragone    | 项目源码 | 文件源码
def _is_set(obj):
    return isinstance(obj, Set) and all(map(_is_value, obj))
项目:pymzn    作者:paolodragone    | 项目源码 | 文件源码
def _is_list(obj):
    return (isinstance(obj, Sized) and isinstance(obj, Iterable) and
            not isinstance(obj, (Set, Mapping)))
项目:stellarmagnate    作者:abadger    | 项目源码 | 文件源码
def recalculate_prices(self):
        """Set new prices for all the commodities in the market"""
        for commodity in self.commodities:
            self._calculate_price(commodity)
项目:driveboardapp    作者:nortd    | 项目源码 | 文件源码
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.)
项目:stig    作者:rndusr    | 项目源码 | 文件源码
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)
项目:stig    作者:rndusr    | 项目源码 | 文件源码
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,)
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
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())
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
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))
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
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
项目:sublimeTextConfig    作者:luoye-fe    | 项目源码 | 文件源码
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)
项目:sublimeTextConfig    作者:luoye-fe    | 项目源码 | 文件源码
def __subclasscheck__(self, cls):
        if issubclass(cls, Set):
            return False
        return super().__subclasscheck__(cls)
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
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())
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
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))
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
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)
项目:multiset    作者:wheerd    | 项目源码 | 文件源码
def __sub__(self, other):
        if isinstance(other, (BaseMultiset, set, frozenset)):
            pass
        elif not isinstance(other, Set):
            return NotImplemented
        return self.difference(other)
项目:multiset    作者:wheerd    | 项目源码 | 文件源码
def __or__(self, other):
        if isinstance(other, (BaseMultiset, set, frozenset)):
            pass
        elif not isinstance(other, Set):
            return NotImplemented
        return self.union(other)
项目:multiset    作者:wheerd    | 项目源码 | 文件源码
def __add__(self, other):
        if isinstance(other, (BaseMultiset, set, frozenset)):
            pass
        elif not isinstance(other, Set):
            return NotImplemented
        return self.combine(other)
项目:multiset    作者:wheerd    | 项目源码 | 文件源码
def __and__(self, other):
        if isinstance(other, (BaseMultiset, set, frozenset)):
            pass
        elif not isinstance(other, Set):
            return NotImplemented
        return self.intersection(other)
项目:multiset    作者:wheerd    | 项目源码 | 文件源码
def __xor__(self, other):
        if isinstance(other, (BaseMultiset, set, frozenset)):
            pass
        elif not isinstance(other, Set):
            return NotImplemented
        return self.symmetric_difference(other)
项目:multiset    作者:wheerd    | 项目源码 | 文件源码
def __lt__(self, other):
        if isinstance(other, (BaseMultiset, set, frozenset)):
            pass
        elif not isinstance(other, Set):
            return NotImplemented
        return self._issubset(other, True)
项目:multiset    作者:wheerd    | 项目源码 | 文件源码
def __ge__(self, other):
        if isinstance(other, (BaseMultiset, set, frozenset)):
            pass
        elif not isinstance(other, Set):
            return NotImplemented
        return self._issuperset(other, False)
项目:multiset    作者:wheerd    | 项目源码 | 文件源码
def __gt__(self, other):
        if isinstance(other, (BaseMultiset, set, frozenset)):
            pass
        elif not isinstance(other, Set):
            return NotImplemented
        return self._issuperset(other, True)
项目:multiset    作者:wheerd    | 项目源码 | 文件源码
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)
项目:multiset    作者:wheerd    | 项目源码 | 文件源码
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)
项目:multiset    作者:wheerd    | 项目源码 | 文件源码
def __ior__(self, other):
        if isinstance(other, (BaseMultiset, set, frozenset)):
            pass
        elif not isinstance(other, Set):
            return NotImplemented
        self.union_update(other)
        return self
项目:multiset    作者:wheerd    | 项目源码 | 文件源码
def __iand__(self, other):
        if isinstance(other, (BaseMultiset, set, frozenset)):
            pass
        elif not isinstance(other, Set):
            return NotImplemented
        self.intersection_update(other)
        return self
项目:multiset    作者:wheerd    | 项目源码 | 文件源码
def __isub__(self, other):
        if isinstance(other, (BaseMultiset, set, frozenset)):
            pass
        elif not isinstance(other, Set):
            return NotImplemented
        self.difference_update(other)
        return self
项目:multiset    作者:wheerd    | 项目源码 | 文件源码
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
项目:kbe_server    作者:xiaohaoppy    | 项目源码 | 文件源码
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())
项目:kbe_server    作者:xiaohaoppy    | 项目源码 | 文件源码
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))
项目:kbe_server    作者:xiaohaoppy    | 项目源码 | 文件源码
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)
项目:mac-package-build    作者:persepolisdm    | 项目源码 | 文件源码
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.)
项目:meta    作者:Ejhfast    | 项目源码 | 文件源码
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)
项目:meta    作者:Ejhfast    | 项目源码 | 文件源码
def __subclasscheck__(self, cls):
        if issubclass(cls, Set):
            return False
        return super().__subclasscheck__(cls)
项目:meta    作者:Ejhfast    | 项目源码 | 文件源码
def __instancecheck__(self, obj):
        if issubclass(obj.__class__, Set):
            return False
        return super().__instancecheck__(obj)
项目:emitjson    作者:atsuoishimoto    | 项目源码 | 文件源码
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