python类Set()的实例源码

test_collections.py 文件源码 项目:web_ctp 作者: molebot 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
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)])
selection.py 文件源码 项目:mastic 作者: ADicksonLab 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
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)
typing.py 文件源码 项目:sublimeTextConfig 作者: luoye-fe 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
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
test_collections.py 文件源码 项目:ouroboros 作者: pybee 项目源码 文件源码 阅读 16 收藏 0 点赞 0 评论 0
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)])
test_collections.py 文件源码 项目:kbe_server 作者: xiaohaoppy 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
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)])
freeze.py 文件源码 项目:phredutils 作者: doctaphred 项目源码 文件源码 阅读 14 收藏 0 点赞 0 评论 0
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
freeze.py 文件源码 项目:phredutils 作者: doctaphred 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
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)))
marsh.py 文件源码 项目:pymzn 作者: paolodragone 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def _is_set(obj):
    return isinstance(obj, Set) and all(map(_is_value, obj))
marsh.py 文件源码 项目:pymzn 作者: paolodragone 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def _is_list(obj):
    return (isinstance(obj, Sized) and isinstance(obj, Iterable) and
            not isinstance(obj, (Set, Mapping)))
market.py 文件源码 项目:stellarmagnate 作者: abadger 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def recalculate_prices(self):
        """Set new prices for all the commodities in the market"""
        for commodity in self.commodities:
            self._calculate_price(commodity)
compat.py 文件源码 项目:driveboardapp 作者: nortd 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
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.)
filelist.py 文件源码 项目:stig 作者: rndusr 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
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)
filelist.py 文件源码 项目:stig 作者: rndusr 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
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,)
test_collections.py 文件源码 项目:web_ctp 作者: molebot 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
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())
test_collections.py 文件源码 项目:web_ctp 作者: molebot 项目源码 文件源码 阅读 16 收藏 0 点赞 0 评论 0
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))
test_collections.py 文件源码 项目:web_ctp 作者: molebot 项目源码 文件源码 阅读 15 收藏 0 点赞 0 评论 0
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
typing.py 文件源码 项目:sublimeTextConfig 作者: luoye-fe 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
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)
typing.py 文件源码 项目:sublimeTextConfig 作者: luoye-fe 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def __subclasscheck__(self, cls):
        if issubclass(cls, Set):
            return False
        return super().__subclasscheck__(cls)
test_collections.py 文件源码 项目:ouroboros 作者: pybee 项目源码 文件源码 阅读 15 收藏 0 点赞 0 评论 0
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())
test_collections.py 文件源码 项目:ouroboros 作者: pybee 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
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))
test_collections.py 文件源码 项目:ouroboros 作者: pybee 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
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.py 文件源码 项目:multiset 作者: wheerd 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def __sub__(self, other):
        if isinstance(other, (BaseMultiset, set, frozenset)):
            pass
        elif not isinstance(other, Set):
            return NotImplemented
        return self.difference(other)
multiset.py 文件源码 项目:multiset 作者: wheerd 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def __or__(self, other):
        if isinstance(other, (BaseMultiset, set, frozenset)):
            pass
        elif not isinstance(other, Set):
            return NotImplemented
        return self.union(other)
multiset.py 文件源码 项目:multiset 作者: wheerd 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def __add__(self, other):
        if isinstance(other, (BaseMultiset, set, frozenset)):
            pass
        elif not isinstance(other, Set):
            return NotImplemented
        return self.combine(other)
multiset.py 文件源码 项目:multiset 作者: wheerd 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def __and__(self, other):
        if isinstance(other, (BaseMultiset, set, frozenset)):
            pass
        elif not isinstance(other, Set):
            return NotImplemented
        return self.intersection(other)
multiset.py 文件源码 项目:multiset 作者: wheerd 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def __xor__(self, other):
        if isinstance(other, (BaseMultiset, set, frozenset)):
            pass
        elif not isinstance(other, Set):
            return NotImplemented
        return self.symmetric_difference(other)
multiset.py 文件源码 项目:multiset 作者: wheerd 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def __lt__(self, other):
        if isinstance(other, (BaseMultiset, set, frozenset)):
            pass
        elif not isinstance(other, Set):
            return NotImplemented
        return self._issubset(other, True)
multiset.py 文件源码 项目:multiset 作者: wheerd 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def __ge__(self, other):
        if isinstance(other, (BaseMultiset, set, frozenset)):
            pass
        elif not isinstance(other, Set):
            return NotImplemented
        return self._issuperset(other, False)
multiset.py 文件源码 项目:multiset 作者: wheerd 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def __gt__(self, other):
        if isinstance(other, (BaseMultiset, set, frozenset)):
            pass
        elif not isinstance(other, Set):
            return NotImplemented
        return self._issuperset(other, True)
multiset.py 文件源码 项目:multiset 作者: wheerd 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
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)


问题


面经


文章

微信
公众号

扫码关注公众号