Python collections.UserDict() Examples

The following are 30 code examples of collections.UserDict(). 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 , or try the search function .
Example #1
Source File: test_inspect.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
def test_multiple_features(self):
        f = self.makeCallable('a, b=2, *f, **g')
        self.assertEqualCallArgs(f, '2, 3, 7')
        self.assertEqualCallArgs(f, '2, 3, x=8')
        self.assertEqualCallArgs(f, '2, 3, x=8, *[(4,[5,6]), 7]')
        self.assertEqualCallArgs(f, '2, x=8, *[3, (4,[5,6]), 7], y=9')
        self.assertEqualCallArgs(f, 'x=8, *[2, 3, (4,[5,6])], y=9')
        self.assertEqualCallArgs(f, 'x=8, *collections.UserList('
                                 '[2, 3, (4,[5,6])]), **{"y":9, "z":10}')
        self.assertEqualCallArgs(f, '2, x=8, *collections.UserList([3, '
                                 '(4,[5,6])]), **collections.UserDict('
                                 'y=9, z=10)')

        f = self.makeCallable('a, b=2, *f, x, y=99, **g')
        self.assertEqualCallArgs(f, '2, 3, x=8')
        self.assertEqualCallArgs(f, '2, 3, x=8, *[(4,[5,6]), 7]')
        self.assertEqualCallArgs(f, '2, x=8, *[3, (4,[5,6]), 7], y=9, z=10')
        self.assertEqualCallArgs(f, 'x=8, *[2, 3, (4,[5,6])], y=9, z=10')
        self.assertEqualCallArgs(f, 'x=8, *collections.UserList('
                                 '[2, 3, (4,[5,6])]), q=0, **{"y":9, "z":10}')
        self.assertEqualCallArgs(f, '2, x=8, *collections.UserList([3, '
                                 '(4,[5,6])]), q=0, **collections.UserDict('
                                 'y=9, z=10)') 
Example #2
Source File: image_test.py    From python-docs-samples with Apache License 2.0 6 votes vote down vote up
def test_process_safe_image(
  storage_client,
  vision_client,
  __blur_image,
  capsys):
    result = UserDict()
    result.safe_search_annotation = UserDict()
    result.safe_search_annotation.adult = 1
    result.safe_search_annotation.violence = 1
    vision_client.safe_search_detection = MagicMock(return_value=result)

    filename = str(uuid.uuid4())
    data = {
      'bucket': 'my-bucket',
      'name': filename
    }

    image.blur_offensive_images(data)

    out, _ = capsys.readouterr()

    assert 'Analyzing %s.' % filename in out
    assert 'The image %s was detected as OK.' % filename in out
    assert __blur_image.called is False 
Example #3
Source File: test_json.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_custom_asserts(self):
        # This would always trigger the KeyError from trying to put
        # an array of equal-length UserDicts inside an ndarray.
        data = JSONArray([collections.UserDict({'a': 1}),
                          collections.UserDict({'b': 2}),
                          collections.UserDict({'c': 3})])
        a = pd.Series(data)
        self.assert_series_equal(a, a)
        self.assert_frame_equal(a.to_frame(), a.to_frame())

        b = pd.Series(data.take([0, 0, 1]))
        with pytest.raises(AssertionError):
            self.assert_series_equal(a, b)

        with pytest.raises(AssertionError):
            self.assert_frame_equal(a.to_frame(), b.to_frame()) 
Example #4
Source File: main_test.py    From python-docs-samples with Apache License 2.0 6 votes vote down vote up
def test_avoid_infinite_retries(capsys):
    now = datetime.now(timezone.utc)

    with patch('main.datetime', wraps=datetime) as datetime_mock:
        datetime_mock.now = Mock(return_value=now)

        old_context = UserDict()
        old_context.timestamp = (now - timedelta(seconds=15)).isoformat()
        old_context.event_id = 'old_event_id'

        young_context = UserDict()
        young_context.timestamp = (now - timedelta(seconds=5)).isoformat()
        young_context.event_id = 'young_event_id'

        main.avoid_infinite_retries(None, old_context)
        out, _ = capsys.readouterr()
        assert f"Dropped {old_context.event_id} (age 15000.0ms)" in out

        main.avoid_infinite_retries(None, young_context)
        out, _ = capsys.readouterr()
        assert f"Processed {young_context.event_id} (age 5000.0ms)" in out 
Example #5
Source File: main_test.py    From python-docs-samples with Apache License 2.0 6 votes vote down vote up
def test_process_safe_image(
  storage_client,
  vision_client,
  __blur_image,
  capsys):
    result = UserDict()
    result.safe_search_annotation = UserDict()
    result.safe_search_annotation.adult = 1
    result.safe_search_annotation.violence = 1
    vision_client.safe_search_detection = MagicMock(return_value=result)

    filename = str(uuid.uuid4())
    data = {
      'bucket': 'my-bucket',
      'name': filename
    }

    main.blur_offensive_images(data, None)

    out, _ = capsys.readouterr()

    assert 'Analyzing %s.' % filename in out
    assert 'The image %s was detected as OK.' % filename in out
    assert __blur_image.called is False 
Example #6
Source File: __init__.py    From jx-sqlite with Mozilla Public License 2.0 6 votes vote down vote up
def __init__(*args, **kwargs):
            if not args:
                raise TypeError("descriptor '__init__' of 'UserDict' object "
                                "needs an argument")
            self, args = args[0], args[1:]
            if len(args) > 1:
                raise TypeError('expected at most 1 arguments, got %d' % len(args))
            if args:
                dict = args[0]
            elif 'dict' in kwargs:
                dict = kwargs.pop('dict')
                import warnings
                warnings.warn("Passing 'dict' as keyword argument is deprecated",
                              DeprecationWarning, stacklevel=2)
            else:
                dict = None
            self.data = {}
            if dict is not None:
                self.update(dict)
            if len(kwargs):
                self.update(kwargs) 
Example #7
Source File: main_test.py    From python-docs-samples with Apache License 2.0 6 votes vote down vote up
def test_process_offensive_image(
  storage_client,
  vision_client,
  __blur_image,
  capsys):
    result = UserDict()
    result.safe_search_annotation = UserDict()
    result.safe_search_annotation.adult = 5
    result.safe_search_annotation.violence = 5
    vision_client.safe_search_detection = MagicMock(return_value=result)

    filename = str(uuid.uuid4())
    data = {
      'bucket': 'my-bucket',
      'name': filename
    }

    main.blur_offensive_images(data, None)

    out, _ = capsys.readouterr()
    assert 'Analyzing %s.' % filename in out
    assert 'The image %s was detected as inappropriate.' % filename in out
    assert main.__blur_image.called 
Example #8
Source File: test_auth.py    From backend.ai-manager with GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_extract_auth_params():
    request = UserDict()

    request.headers = {}
    assert _extract_auth_params(request) is None

    request.headers = {'Authorization': 'no-space'}
    with pytest.raises(InvalidAuthParameters):
        _extract_auth_params(request)

    request.headers = {'Authorization': ('BadAuthType signMethod=HMAC-SHA256,'
                                         'credential=fake-ak:fake-sig')}
    with pytest.raises(InvalidAuthParameters):
        _extract_auth_params(request)

    request.headers = {'Authorization': ('BackendAI signMethod=HMAC-SHA256,'
                                         'credential=fake-ak:fake-sig')}
    ret = _extract_auth_params(request)
    assert ret[0] == 'HMAC-SHA256'
    assert ret[1] == 'fake-ak'
    assert ret[2] == 'fake-sig' 
Example #9
Source File: test_json.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def test_custom_asserts(self):
        # This would always trigger the KeyError from trying to put
        # an array of equal-length UserDicts inside an ndarray.
        data = JSONArray([collections.UserDict({'a': 1}),
                          collections.UserDict({'b': 2}),
                          collections.UserDict({'c': 3})])
        a = pd.Series(data)
        self.assert_series_equal(a, a)
        self.assert_frame_equal(a.to_frame(), a.to_frame())

        b = pd.Series(data.take([0, 0, 1]))
        with pytest.raises(AssertionError):
            self.assert_series_equal(a, b)

        with pytest.raises(AssertionError):
            self.assert_frame_equal(a.to_frame(), b.to_frame()) 
Example #10
Source File: test_inspect.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
def test_plain(self):
        f = self.makeCallable('a, b=1')
        self.assertEqualCallArgs(f, '2')
        self.assertEqualCallArgs(f, '2, 3')
        self.assertEqualCallArgs(f, 'a=2')
        self.assertEqualCallArgs(f, 'b=3, a=2')
        self.assertEqualCallArgs(f, '2, b=3')
        # expand *iterable / **mapping
        self.assertEqualCallArgs(f, '*(2,)')
        self.assertEqualCallArgs(f, '*[2]')
        self.assertEqualCallArgs(f, '*(2, 3)')
        self.assertEqualCallArgs(f, '*[2, 3]')
        self.assertEqualCallArgs(f, '**{"a":2}')
        self.assertEqualCallArgs(f, 'b=3, **{"a":2}')
        self.assertEqualCallArgs(f, '2, **{"b":3}')
        self.assertEqualCallArgs(f, '**{"b":3, "a":2}')
        # expand UserList / UserDict
        self.assertEqualCallArgs(f, '*collections.UserList([2])')
        self.assertEqualCallArgs(f, '*collections.UserList([2, 3])')
        self.assertEqualCallArgs(f, '**collections.UserDict(a=2)')
        self.assertEqualCallArgs(f, '2, **collections.UserDict(b=3)')
        self.assertEqualCallArgs(f, 'b=2, **collections.UserDict(a=3)') 
Example #11
Source File: pickletester.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
def test_compat_pickle(self):
        tests = [
            (range(1, 7), '__builtin__', 'xrange'),
            (map(int, '123'), 'itertools', 'imap'),
            (functools.reduce, '__builtin__', 'reduce'),
            (dbm.whichdb, 'whichdb', 'whichdb'),
            (Exception(), 'exceptions', 'Exception'),
            (collections.UserDict(), 'UserDict', 'IterableUserDict'),
            (collections.UserList(), 'UserList', 'UserList'),
            (collections.defaultdict(), 'collections', 'defaultdict'),
        ]
        for val, mod, name in tests:
            for proto in range(3):
                with self.subTest(type=type(val), proto=proto):
                    pickled = self.dumps(val, proto)
                    self.assertIn(('c%s\n%s' % (mod, name)).encode(), pickled)
                    self.assertIs(type(self.loads(pickled)), type(val)) 
Example #12
Source File: test_misc.py    From http-observatory with Mozilla Public License 2.0 6 votes vote down vote up
def test_redirects_to_https_with_port_number(self):
        # same thing, but with :443 on the URL, see issue #180
        self.reqs['responses']['http'].url = 'https://http-observatory.security.mozilla.org:443/'

        history1 = UserDict()
        history1.request = UserDict()
        history1.request.url = 'http://http-observatory.security.mozilla.org/'

        self.reqs['responses']['http'].history.append(history1)

        result = redirection(self.reqs)

        self.assertEquals('redirection-to-https', result['result'])
        self.assertEquals(['http://http-observatory.security.mozilla.org/',
                           'https://http-observatory.security.mozilla.org:443/'], result['route'])
        self.assertTrue(result['pass']) 
Example #13
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 #14
Source File: test_json.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 6 votes vote down vote up
def test_custom_asserts(self):
        # This would always trigger the KeyError from trying to put
        # an array of equal-length UserDicts inside an ndarray.
        data = JSONArray([collections.UserDict({'a': 1}),
                          collections.UserDict({'b': 2}),
                          collections.UserDict({'c': 3})])
        a = pd.Series(data)
        self.assert_series_equal(a, a)
        self.assert_frame_equal(a.to_frame(), a.to_frame())

        b = pd.Series(data.take([0, 0, 1]))
        with pytest.raises(AssertionError):
            self.assert_series_equal(a, b)

        with pytest.raises(AssertionError):
            self.assert_frame_equal(a.to_frame(), b.to_frame()) 
Example #15
Source File: test_inspect.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def test_multiple_features(self):
        f = self.makeCallable('a, b=2, *f, **g')
        self.assertEqualCallArgs(f, '2, 3, 7')
        self.assertEqualCallArgs(f, '2, 3, x=8')
        self.assertEqualCallArgs(f, '2, 3, x=8, *[(4,[5,6]), 7]')
        self.assertEqualCallArgs(f, '2, x=8, *[3, (4,[5,6]), 7], y=9')
        self.assertEqualCallArgs(f, 'x=8, *[2, 3, (4,[5,6])], y=9')
        self.assertEqualCallArgs(f, 'x=8, *collections.UserList('
                                 '[2, 3, (4,[5,6])]), **{"y":9, "z":10}')
        self.assertEqualCallArgs(f, '2, x=8, *collections.UserList([3, '
                                 '(4,[5,6])]), **collections.UserDict('
                                 'y=9, z=10)')

        f = self.makeCallable('a, b=2, *f, x, y=99, **g')
        self.assertEqualCallArgs(f, '2, 3, x=8')
        self.assertEqualCallArgs(f, '2, 3, x=8, *[(4,[5,6]), 7]')
        self.assertEqualCallArgs(f, '2, x=8, *[3, (4,[5,6]), 7], y=9, z=10')
        self.assertEqualCallArgs(f, 'x=8, *[2, 3, (4,[5,6])], y=9, z=10')
        self.assertEqualCallArgs(f, 'x=8, *collections.UserList('
                                 '[2, 3, (4,[5,6])]), q=0, **{"y":9, "z":10}')
        self.assertEqualCallArgs(f, '2, x=8, *collections.UserList([3, '
                                 '(4,[5,6])]), q=0, **collections.UserDict('
                                 'y=9, z=10)') 
Example #16
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 #17
Source File: test_misc.py    From http-observatory with Mozilla Public License 2.0 6 votes vote down vote up
def test_all_redirections_preloaded(self):
        self.reqs['responses']['http'].url = 'https://www.pokeinthe.io/foo/bar'

        for url in ('http://pokeinthe.io/',
                    'https://pokeinthe.io/',
                    'https://www.pokeinthe.io/',
                    'https://baz.pokeinthe.io/foo'):
            history = UserDict()
            history.request = UserDict()
            history.request.url = url

            self.reqs['responses']['http'].history.append(history)

        result = redirection(self.reqs)

        self.assertEquals('redirection-all-redirects-preloaded', result['result'])
        self.assertTrue(result['pass']) 
Example #18
Source File: pickletester.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def test_compat_pickle(self):
        tests = [
            (range(1, 7), '__builtin__', 'xrange'),
            (map(int, '123'), 'itertools', 'imap'),
            (functools.reduce, '__builtin__', 'reduce'),
            (dbm.whichdb, 'whichdb', 'whichdb'),
            (Exception(), 'exceptions', 'Exception'),
            (collections.UserDict(), 'UserDict', 'IterableUserDict'),
            (collections.UserList(), 'UserList', 'UserList'),
            (collections.defaultdict(), 'collections', 'defaultdict'),
        ]
        for val, mod, name in tests:
            for proto in range(3):
                with self.subTest(type=type(val), proto=proto):
                    pickled = self.dumps(val, proto)
                    self.assertIn(('c%s\n%s' % (mod, name)).encode(), pickled)
                    self.assertIs(type(self.loads(pickled)), type(val)) 
Example #19
Source File: test_misc.py    From http-observatory with Mozilla Public License 2.0 6 votes vote down vote up
def test_first_redirection_still_http(self):
        self.reqs['responses']['http'].url = 'https://http-observatory.security.mozilla.org/foo'

        history1 = UserDict()
        history1.request = UserDict()
        history1.request.url = 'http://http-observatory.security.mozilla.org/'

        history2 = UserDict()
        history2.request = UserDict()
        history2.request.url = 'http://http-observatory.security.mozilla.org/foo'

        self.reqs['responses']['http'].history.append(history1)
        self.reqs['responses']['http'].history.append(history2)

        result = redirection(self.reqs)

        self.assertEquals('redirection-not-to-https-on-initial-redirection', result['result'])
        self.assertFalse(result['pass']) 
Example #20
Source File: test_inspect.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def test_plain(self):
        f = self.makeCallable('a, b=1')
        self.assertEqualCallArgs(f, '2')
        self.assertEqualCallArgs(f, '2, 3')
        self.assertEqualCallArgs(f, 'a=2')
        self.assertEqualCallArgs(f, 'b=3, a=2')
        self.assertEqualCallArgs(f, '2, b=3')
        # expand *iterable / **mapping
        self.assertEqualCallArgs(f, '*(2,)')
        self.assertEqualCallArgs(f, '*[2]')
        self.assertEqualCallArgs(f, '*(2, 3)')
        self.assertEqualCallArgs(f, '*[2, 3]')
        self.assertEqualCallArgs(f, '**{"a":2}')
        self.assertEqualCallArgs(f, 'b=3, **{"a":2}')
        self.assertEqualCallArgs(f, '2, **{"b":3}')
        self.assertEqualCallArgs(f, '**{"b":3, "a":2}')
        # expand UserList / UserDict
        self.assertEqualCallArgs(f, '*collections.UserList([2])')
        self.assertEqualCallArgs(f, '*collections.UserList([2, 3])')
        self.assertEqualCallArgs(f, '**collections.UserDict(a=2)')
        self.assertEqualCallArgs(f, '2, **collections.UserDict(b=3)')
        self.assertEqualCallArgs(f, 'b=2, **collections.UserDict(a=3)') 
Example #21
Source File: avpair.py    From msldap with MIT License 5 votes vote down vote up
def __init__(self, data = None):
		collections.UserDict.__init__(self, data) 
Example #22
Source File: test_userdict.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_update(self):
        for kw in 'self', 'dict', 'other', 'iterable':
            d = collections.UserDict()
            d.update(**{kw: 42})
            self.assertEqual(list(d.items()), [(kw, 42)])
        self.assertRaises(TypeError, collections.UserDict().update, 42)
        self.assertRaises(TypeError, collections.UserDict().update, {}, {})
        self.assertRaises(TypeError, collections.UserDict.update) 
Example #23
Source File: test_userdict.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_init(self):
        for kw in 'self', 'other', 'iterable':
            self.assertEqual(list(collections.UserDict(**{kw: 42}).items()),
                             [(kw, 42)])
        self.assertEqual(list(collections.UserDict({}, dict=42).items()),
                         [('dict', 42)])
        self.assertEqual(list(collections.UserDict({}, dict=None).items()),
                         [('dict', None)])
        with self.assertWarnsRegex(PendingDeprecationWarning, "'dict'"):
            self.assertEqual(list(collections.UserDict(dict={'a': 42}).items()),
                             [('a', 42)])
        self.assertRaises(TypeError, collections.UserDict, 42)
        self.assertRaises(TypeError, collections.UserDict, (), ())
        self.assertRaises(TypeError, collections.UserDict.__init__) 
Example #24
Source File: batch.py    From Jacinle with MIT License 5 votes vote down vote up
def unbatchify(inputs):
    if isinstance(inputs, (tuple, list, collections.UserList)):
        outputs = [unbatchify(e) for e in inputs]
        return list(map(list, zip(*outputs)))
    elif isinstance(inputs, (collections.Mapping, collections.UserDict)):
        outputs = {k: unbatchify(v) for k, v in inputs.items()}
        first = outputs[0]
        return [{k: outputs[k][i] for k in inputs} for i in range(len(first))]
    return list(inputs) 
Example #25
Source File: test_inspect.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_varkw_only(self):
        # issue11256:
        f = self.makeCallable('**c')
        self.assertEqualCallArgs(f, '')
        self.assertEqualCallArgs(f, 'a=1')
        self.assertEqualCallArgs(f, 'a=1, b=2')
        self.assertEqualCallArgs(f, 'c=3, **{"a": 1, "b": 2}')
        self.assertEqualCallArgs(f, '**collections.UserDict(a=1, b=2)')
        self.assertEqualCallArgs(f, 'c=3, **collections.UserDict(a=1, b=2)') 
Example #26
Source File: test_misc.py    From http-observatory with Mozilla Public License 2.0 5 votes vote down vote up
def test_redirection_not_to_https(self):
        self.reqs['responses']['http'].url = 'http://http-observatory.security.mozilla.org/foo'

        history1 = UserDict()
        history1.request = UserDict()
        history1.request.url = 'http://http-observatory.security.mozilla.org/'

        self.reqs['responses']['http'].history.append(history1)

        result = redirection(self.reqs)

        self.assertEquals('redirection-not-to-https', result['result'])
        self.assertFalse(result['pass']) 
Example #27
Source File: test_inspect.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_varkw(self):
        f = self.makeCallable('a, b=1, **c')
        self.assertEqualCallArgs(f, 'a=2')
        self.assertEqualCallArgs(f, '2, b=3, c=4')
        self.assertEqualCallArgs(f, 'b=3, a=2, c=4')
        self.assertEqualCallArgs(f, 'c=4, **{"a":2, "b":3}')
        self.assertEqualCallArgs(f, '2, c=4, **{"b":3}')
        self.assertEqualCallArgs(f, 'b=2, **{"a":3, "c":4}')
        self.assertEqualCallArgs(f, '**collections.UserDict(a=2, b=3, c=4)')
        self.assertEqualCallArgs(f, '2, c=4, **collections.UserDict(b=3)')
        self.assertEqualCallArgs(f, 'b=2, **collections.UserDict(a=3, c=4)') 
Example #28
Source File: Builder.py    From sitoa with Apache License 2.0 5 votes vote down vote up
def __init__(self, dict):
        collections.UserDict.__init__(self, dict)
        if __debug__: logInstanceCreation(self, 'Builder.OverrideWarner')
        self.already_warned = None 
Example #29
Source File: __init__.py    From jx-sqlite with Mozilla Public License 2.0 5 votes vote down vote up
def copy(self):
            if self.__class__ is UserDict:
                return UserDict(self.data.copy())
            import copy
            data = self.data
            try:
                self.data = {}
                c = copy.copy(self)
            finally:
                self.data = data
            c.update(self)
            return c 
Example #30
Source File: meta.py    From Jacinle with MIT License 5 votes vote down vote up
def stmap(func, iterable):
    if isinstance(iterable, six.string_types):
        return func(iterable)
    elif isinstance(iterable, (collections.Sequence, collections.UserList)):
        return [stmap(func, v) for v in iterable]
    elif isinstance(iterable, collections.Set):
        return {stmap(func, v) for v in iterable}
    elif isinstance(iterable, (collections.Mapping, collections.UserDict)):
        return {k: stmap(func, v) for k, v in iterable.items()}
    else:
        return func(iterable)