Python collections.abc.KeysView() Examples

The following are 13 code examples of collections.abc.KeysView(). 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 also want to check out all available functions/classes of the module collections.abc , or try the search function .
Example #1
Source File: serialization.py    From Penny-Dreadful-Tools with GNU General Public License v3.0 6 votes vote down vote up
def extra_serializer(obj: Any) -> Union[int, str, List[Any], Dict[str, Any]]:
    """JSON serializer for objects not serializable by default json code"""

    if isinstance(obj, datetime.datetime):
        return dtutil.dt2ts(obj)
    if isinstance(obj, bytes):
        return obj.decode('utf-8')
    if isinstance(obj, decimal.Decimal):
        return obj.to_eng_string()
    if isinstance(obj, (set, KeysView)):
        return list(obj)
    if isinstance(obj, Exception):
        stack = traceback.extract_tb(obj.__traceback__)
        return traceback.format_list(stack)
    if hasattr(obj, 'to_dict'):
        return obj.to_dict()
    if hasattr(obj, '__attrs_attrs__'):
        val: Dict[str, Any] = {}
        for a in obj.__attrs_attrs__:
            val[a.name] = getattr(obj, a.name)
        return val
    raise TypeError('Type {t} not serializable - {obj}'.format(t=type(obj), obj=obj)) 
Example #2
Source File: test_collections.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
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)]) 
Example #3
Source File: test_collections.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
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)]) 
Example #4
Source File: test_collections.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 6 votes vote down vote up
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)]) 
Example #5
Source File: test_collections.py    From android_universal with MIT License 6 votes vote down vote up
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)]) 
Example #6
Source File: bqm.py    From dimod with Apache License 2.0 5 votes vote down vote up
def variables(self):
        """The variables of the binary quadratic model."""
        return KeysView(self.linear) 
Example #7
Source File: _methods.py    From pikepdf with Mozilla Public License 2.0 5 votes vote down vote up
def keys(self):
        return KeysView(self) 
Example #8
Source File: utils.py    From scvelo with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def make_unique_list(key, allow_array=False):
    if isinstance(key, (Index, abc.KeysView)):
        key = list(key)
    is_list = (
        isinstance(key, (list, tuple, np.record))
        if allow_array
        else isinstance(key, (list, tuple, np.ndarray, np.record))
    )
    is_list_of_str = is_list and all(isinstance(item, str) for item in key)
    return key if is_list_of_str else key if is_list and len(key) < 20 else [key] 
Example #9
Source File: __init__.py    From aws-cfn-template-flip with Apache License 2.0 5 votes vote down vote up
def has_intrinsic_functions(parameter):
    intrinsic_functions = ["Fn::Sub", "!Sub", "!GetAtt"]
    result = False
    if isinstance(parameter, (list, tuple, dict, KeysView)):
        for item in parameter:
            if item in intrinsic_functions:
                result = True
                break
    return result 
Example #10
Source File: resources.py    From forte with Apache License 2.0 5 votes vote down vote up
def keys(self) -> KeysView:
        r"""Return all keys of the resources.
        """
        return self.resources.keys() 
Example #11
Source File: utils.py    From xarray-simlab with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def keys(self):
        "D.keys() -> a set-like object providing a view on D's keys"
        return KeysView(self) 
Example #12
Source File: _mutablemapping.py    From compas with MIT License 5 votes vote down vote up
def keys(self):
        """D.keys() => a set-like object providing a view on D's keys"""
        return stdlib_collections.KeysView(self) 
Example #13
Source File: utils.py    From sos with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def short_repr(obj, noneAsNA=False):
    '''Return a short representation of obj for clarity.'''
    if obj is None:
        return 'unspecified' if noneAsNA else 'None'
    elif isinstance(obj, str) and len(obj) > 80:
        return '{}...{}'.format(obj[:60].replace('\n', '\\n'),
                                obj[-20:].replace('\n', '\\n'))
    elif isinstance(obj, (str, int, float, bool)):
        return repr(obj)
    elif hasattr(obj, '__short_repr__'):
        return obj.__short_repr__()
    elif isinstance(obj, Sequence):  # should be a list or tuple
        if len(obj) == 0:
            return '[]'
        elif len(obj) == 1:
            return f'{short_repr(obj[0])}'
        elif len(obj) == 2:
            return f'{short_repr(obj[0])}, {short_repr(obj[1])}'
        else:
            return f'{short_repr(obj[0])}, {short_repr(obj[1])}, ... ({len(obj)} items)'
    elif isinstance(obj, dict):
        if not obj:
            return ''
        elif len(obj) == 1:
            first_key = list(obj.keys())[0]
            return f'{short_repr(first_key)!r}:{short_repr(obj[first_key])!r}'
        else:
            first_key = list(obj.keys())[0]
            return f'{short_repr(first_key)}:{short_repr(obj[first_key])}, ... ({len(obj)} items)'
    elif isinstance(obj, KeysView):
        if not obj:
            return ''
        elif len(obj) == 1:
            return short_repr(next(iter(obj)))
        else:
            return f'{short_repr(next(iter(obj)))}, ... ({len(obj)} items)'
    # elif hasattr(obj, 'target_name'):
    #    return obj.target_name()
    else:
        ret = str(obj)
        if len(ret) > 40:
            return f'{repr(obj)[:35]}...'
        else:
            return ret


#
# SoS Workflow dictionary
#