Python collections.Set() Examples

The following are 30 code examples for showing how to use collections.Set(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may want to check out the right sidebar which shows the related API usage.

You may also want to check out all available functions/classes of the module collections , or try the search function .

Example 1
Project: ironpython2   Author: IronLanguages   File: test_dictviews.py    License: Apache License 2.0 6 votes vote down vote up
def test_abc_registry(self):
        d = dict(a=1)

        self.assertIsInstance(d.viewkeys(), collections.KeysView)
        self.assertIsInstance(d.viewkeys(), collections.MappingView)
        self.assertIsInstance(d.viewkeys(), collections.Set)
        self.assertIsInstance(d.viewkeys(), collections.Sized)
        self.assertIsInstance(d.viewkeys(), collections.Iterable)
        self.assertIsInstance(d.viewkeys(), collections.Container)

        self.assertIsInstance(d.viewvalues(), collections.ValuesView)
        self.assertIsInstance(d.viewvalues(), collections.MappingView)
        self.assertIsInstance(d.viewvalues(), collections.Sized)

        self.assertIsInstance(d.viewitems(), collections.ItemsView)
        self.assertIsInstance(d.viewitems(), collections.MappingView)
        self.assertIsInstance(d.viewitems(), collections.Set)
        self.assertIsInstance(d.viewitems(), collections.Sized)
        self.assertIsInstance(d.viewitems(), collections.Iterable)
        self.assertIsInstance(d.viewitems(), collections.Container) 
Example 2
Project: ngraph-python   Author: NervanaSystems   File: hetrtransform.py    License: Apache License 2.0 6 votes vote down vote up
def __call__(self, *args, **kwargs):
        """
        Executes child computations in parallel.

        :arg args: list of values to the placeholders specified in __init__ *args

        :return: tuple of return values, one per return specified in __init__ returns list.
        """
        args = self.unpack_args_or_feed_dict(args, kwargs)
        for child in itervalues(self.child_computations):
            child.feed_input([args[i] for i in child.param_idx])

        return_vals = dict()
        for child in itervalues(self.child_computations):
            return_vals.update(child.get_results())

        if isinstance(self.computation_op.returns, Op):
            return return_vals[self.computation_op.returns]
        elif isinstance(self.computation_op.returns, (collections.Sequence, OrderedSet)):
            return tuple(return_vals[op] for op in self.computation_op.returns)
        elif isinstance(self.computation_op.returns, collections.Set):
            return return_vals
        else:
            return None 
Example 3
Project: python-gssapi   Author: pythongssapi   File: test_raw.py    License: ISC License 6 votes vote down vote up
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) 
Example 4
Project: n6   Author: CERT-Polska   File: fields.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def _get_main_qualifier_and_additional_info(self, arg_value):
        if (isinstance(arg_value, (collections.Set, collections.Sequence)) and
              not isinstance(arg_value, basestring)):
            # the `in_params`/`in_result` field constructor argument is
            # a set or a sequence (but not a string) -- so we expect that
            # it contains the main qualifier (one of VALID_MAIN_QUALIFIERS)
            # and possibly also other items (which we will isolate and place
            # in the `additional_info` frozenset)
            (main_qualifier,
             additional_info) = self._extract_components(arg_value)
        else:
            # otherwise we expect it to be just the main qualifier or None
            # (as in n6sdk)
            if arg_value is not None and arg_value not in VALID_MAIN_QUALIFIERS:
                raise ValueError(
                    "if not None it should be a valid main qualifier "
                    "(one of: {}) or a set/sequence containing it".format(
                        ', '.join(sorted(map(repr, VALID_MAIN_QUALIFIERS)))))
            main_qualifier = arg_value
            additional_info = frozenset()
        assert main_qualifier is None and not additional_info or (
            main_qualifier in VALID_MAIN_QUALIFIERS and
            not (additional_info & VALID_MAIN_QUALIFIERS))
        return main_qualifier, additional_info 
Example 5
Project: n6   Author: CERT-Polska   File: _generic_helpers.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def assertEqualIncludingTypes(self, first, second, msg=None):
        self.assertEqual(first, second)
        if first is not mock.ANY and second is not mock.ANY:
            self.assertIs(type(first), type(second),
                          'type of {!r} ({}) is not type of {!r} ({})'
                          .format(first, type(first), second, type(second)))
        if isinstance(first, collections.Sequence) and not isinstance(first, basestring):
            for val1, val2 in zip(first, second):
                self.assertEqualIncludingTypes(val1, val2)
        elif isinstance(first, collections.Set):
            for val1, val2 in zip(sorted(first, key=self._safe_sort_key),
                                  sorted(second, key=self._safe_sort_key)):
                self.assertEqualIncludingTypes(val1, val2)
        elif isinstance(first, collections.Mapping):
            for key1, key2 in zip(sorted(first.iterkeys(), key=self._safe_sort_key),
                                  sorted(second.iterkeys(), key=self._safe_sort_key)):
                self.assertEqualIncludingTypes(key1, key2)
            for key in first:
                self.assertEqualIncludingTypes(first[key], second[key]) 
Example 6
Project: code   Author: ActiveState   File: recipe-578039.py    License: MIT License 6 votes vote down vote up
def objview(obj,withValues,path = str()):
    ''' That function will iterate recursivlly accross members of class
        or collections, until all primitives are found '''
    if not len(path): path = type(obj).__name__ 
    iterator = None
    if isinstance(obj, Mapping):
         iterator = iteritems
    else: 
         if isinstance(obj, (Sequence,Set,array.array,deque)) \
            and not isinstance(obj,__string_types__)  and not hasattr(obj,'_asdict'):
            iterator = enumerate
         else: 
            if not type(obj).__name__ in __primitiveTypes__:
               iterator = class__view

    if iterator:
            for path_component, value in iterator(obj):
                valuetype = type(value).__name__ 
                nextpath = path + ('[%s]' % str(path_component)) 
                if (not withValues): yield nextpath, valuetype
                for result in objview(value,withValues,nextpath):               
                    if (withValues or (valuetype not in __primitiveTypes__)):  yield result
    else:
        yield path, obj 
Example 7
Project: stacks   Author: cfstacks   File: cf.py    License: MIT License 6 votes vote down vote up
def traverse_template(obj, obj_path=(), memo=None):
    def iteritems(mapping):
        return getattr(mapping, 'iteritems', mapping.items)()

    if memo is None:
        memo = set()
    iterator = None
    if isinstance(obj, Mapping):
        iterator = iteritems
    elif isinstance(obj, (Sequence, Set)) and not isinstance(obj, (str, bytes)):
        iterator = enumerate
    if iterator:
        if id(obj) not in memo:
            memo.add(id(obj))
            for path_component, value in iterator(obj):
                for result in traverse_template(value, obj_path + (path_component,), memo):
                    yield result
            memo.remove(id(obj))
    else:
        yield obj_path, obj 
Example 8
Project: executing   Author: alexmojaki   File: configuration.py    License: MIT License 6 votes vote down vote up
def len_shape_watch(source, value):
    try:
        shape = value.shape
    except Exception:
        pass
    else:
        if not inspect.ismethod(shape):
            return '{}.shape'.format(source), shape

    if isinstance(value, QuerySet):
        # Getting the length of a Django queryset evaluates it
        return None

    length = len(value)
    if (
            (isinstance(value, six.string_types)
             and length < 50) or
            (isinstance(value, (Mapping, Set, Sequence))
             and length == 0)
    ):
        return None

    return 'len({})'.format(source), length 
Example 9
Project: pyRevit   Author: eirannejad   File: sortedset.py    License: GNU General Public License v3.0 6 votes vote down vote up
def _make_cmp(self, set_op, doc):
        "Make comparator method."
        def comparer(self, that):
            "Compare method for sorted set and set-like object."
            # pylint: disable=protected-access
            if isinstance(that, SortedSet):
                return set_op(self._set, that._set)
            elif isinstance(that, Set):
                return set_op(self._set, that)
            else:
                return NotImplemented

        comparer.__name__ = '__{0}__'.format(set_op.__name__)
        doc_str = 'Return True if and only if Set is {0} `that`.'
        comparer.__doc__ = doc_str.format(doc)

        return comparer 
Example 10
Project: hyperparameter_hunter   Author: HunterMcGushion   File: boltons_utils.py    License: MIT License 6 votes vote down vote up
def default_exit(path, key, old_parent, new_parent, new_items):
    # print('exit(%r, %r, %r, %r, %r)'
    #       % (path, key, old_parent, new_parent, new_items))
    ret = new_parent
    if isinstance(new_parent, Mapping):
        new_parent.update(new_items)
    elif isinstance(new_parent, Sequence):
        vals = [v for i, v in new_items]
        try:
            new_parent.extend(vals)
        except AttributeError:
            ret = new_parent.__class__(vals)  # tuples
    elif isinstance(new_parent, Set):
        vals = [v for i, v in new_items]
        try:
            new_parent.update(vals)
        except AttributeError:
            ret = new_parent.__class__(vals)  # frozensets
    else:
        raise RuntimeError("unexpected iterable type: %r" % type(new_parent))
    return ret 
Example 11
Project: dateparser   Author: scrapinghub   File: search.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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) 
Example 12
Project: SA-ctf_scoreboard   Author: splunk   File: sortedset.py    License: Creative Commons Zero v1.0 Universal 6 votes vote down vote up
def _make_cmp(self, set_op, doc):
        "Make comparator method."
        def comparer(self, that):
            "Compare method for sorted set and set-like object."
            # pylint: disable=protected-access
            if isinstance(that, SortedSet):
                return set_op(self._set, that._set)
            elif isinstance(that, Set):
                return set_op(self._set, that)
            else:
                return NotImplemented

        comparer.__name__ = '__{0}__'.format(set_op.__name__)
        doc_str = 'Return True if and only if Set is {0} `that`.'
        comparer.__doc__ = doc_str.format(doc)

        return comparer 
Example 13
Project: mochi   Author: i2y   File: mailbox.py    License: MIT License 6 votes vote down vote up
def encode(obj):
    if type(obj) in (list, tuple) or isinstance(obj, PVector):
        return [encode(item) for item in obj]
    if isinstance(obj, Mapping):
        encoded_obj = {}
        for key in obj.keys():
            encoded_obj[encode(key)] = encode(obj[key])
        return encoded_obj
    if isinstance(obj, _native_builtin_types):
        return obj
    if isinstance(obj, Set):
        return ExtType(TYPE_PSET, packb([encode(item) for item in obj], use_bin_type=True))
    if isinstance(obj, PList):
        return ExtType(TYPE_PLIST, packb([encode(item) for item in obj], use_bin_type=True))
    if isinstance(obj, PBag):
        return ExtType(TYPE_PBAG, packb([encode(item) for item in obj], use_bin_type=True))
    if isinstance(obj, types.FunctionType):
        return ExtType(TYPE_FUNC, encode_func(obj))
    if isinstance(obj, Receiver):
        return ExtType(TYPE_MBOX, packb(obj.encode(), use_bin_type=True))
    # assume record
    cls = obj.__class__
    return ExtType(0, packb([cls.__module__, cls.__name__] + [encode(item) for item in obj],
                            use_bin_type=True)) 
Example 14
Project: json-spec   Author: johnnoone   File: stages.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def stage(obj, parent=None, member=None):
    """
    Prepare obj to be staged.

    This is almost used for relative JSON Pointers.
    """
    obj = Staged(obj, parent, member)

    if isinstance(obj, Mapping):
        for key, value in obj.items():
            stage(value, obj, key)
    elif isinstance(obj, Sequence) and not isinstance(obj, string_types):
        for index, value in enumerate(obj):
            stage(value, obj, index)
    elif isinstance(obj, Set):
        for value in obj:
            stage(value, obj, None)

    return obj 
Example 15
Project: aws-kube-codesuite   Author: aws-samples   File: reportviews.py    License: Apache License 2.0 6 votes vote down vote up
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) 
Example 16
Project: misp42splunk   Author: remg427   File: sortedset.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
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 
Example 17
Project: misp42splunk   Author: remg427   File: sortedset.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
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 
Example 18
Project: misp42splunk   Author: remg427   File: sortedset.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
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 
Example 19
Project: misp42splunk   Author: remg427   File: sortedset.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
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 
Example 20
Project: linter-pylama   Author: AtomLinter   File: config.py    License: MIT License 5 votes vote down vote up
def _set_add_options(cls, checked_codes, options):
        """Set `checked_codes` by the `add_ignore` or `add_select` options."""
        checked_codes |= cls._expand_error_codes(options.add_select)
        checked_codes -= cls._expand_error_codes(options.add_ignore) 
Example 21
Project: linter-pylama   Author: AtomLinter   File: config.py    License: MIT License 5 votes vote down vote up
def _fix_set_options(cls, options):
        """Alter the set options from None/strings to sets in place."""
        optional_set_options = ('ignore', 'select')
        mandatory_set_options = ('add_ignore', 'add_select')

        def _get_set(value_str):
            """Split `value_str` by the delimiter `,` and return a set.

            Removes any occurrences of '' in the set.
            Also expand error code prefixes, to avoid doing this for every
            file.

            """
            return cls._expand_error_codes(set(value_str.split(',')) - {''})

        for opt in optional_set_options:
            value = getattr(options, opt)
            if value is not None:
                setattr(options, opt, _get_set(value))

        for opt in mandatory_set_options:
            value = getattr(options, opt)
            if value is None:
                value = ''

            if not isinstance(value, Set):
                value = _get_set(value)

            setattr(options, opt, value)

        return options 
Example 22
Project: flask-jwt-extended   Author: vimalloc   File: config.py    License: MIT License 5 votes vote down vote up
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 
Example 23
Project: flask-jwt-extended   Author: vimalloc   File: config.py    License: MIT License 5 votes vote down vote up
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 
Example 24
Project: ironpython2   Author: IronLanguages   File: test_collections.py    License: Apache License 2.0 5 votes vote down vote up
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()) 
Example 25
Project: ironpython2   Author: IronLanguages   File: test_collections.py    License: Apache License 2.0 5 votes vote down vote up
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)) 
Example 26
Project: ironpython2   Author: IronLanguages   File: test_collections.py    License: Apache License 2.0 5 votes vote down vote up
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()

        # Run all the variants to make sure they don't mutually recurse
        ncs < cs
        ncs <= cs
        ncs > cs
        ncs >= cs
        cs < ncs
        cs <= ncs
        cs > ncs
        cs >= ncs 
Example 27
Project: faces   Author: skarlekar   File: types.py    License: GNU General Public License v2.0 5 votes vote down vote up
def _is_set(self, value):
        if isinstance(value, Set):
            return True
        return False 
Example 28
Project: faces   Author: skarlekar   File: types.py    License: GNU General Public License v2.0 5 votes vote down vote up
def _is_set(self, value):
        if isinstance(value, Set):
            return True
        return False 
Example 29
Project: vnpy_crypto   Author: birforce   File: sortedset.py    License: MIT License 5 votes vote down vote up
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 
Example 30
Project: BinderFilter   Author: dxwu   File: test_collections.py    License: MIT License 5 votes vote down vote up
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())