Python operator.getitem() Examples

The following are 30 code examples of operator.getitem(). 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 operator , or try the search function .
Example #1
Source File: irc.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def emit(self):
        """
        Add the currently parsed input to the result.
        """
        if self._buffer:
            attrs = [getattr(attributes, name) for name in self._attrs]
            attrs.extend(filter(None, [self.foreground, self.background]))
            if not attrs:
                attrs.append(attributes.normal)
            attrs.append(self._buffer)

            attr = _foldr(operator.getitem, attrs.pop(), attrs)
            if self._result is None:
                self._result = attr
            else:
                self._result[attr]
            self._buffer = '' 
Example #2
Source File: test_log.py    From attention-lvcsr with MIT License 6 votes vote down vote up
def test_training_log():
    log = TrainingLog()

    # test basic writing capabilities
    log[0]['field'] = 45
    assert log[0]['field'] == 45
    assert log[1] == {}
    assert log.current_row['field'] == 45
    log.status['iterations_done'] += 1
    assert log.status['iterations_done'] == 1
    assert log.previous_row['field'] == 45

    assert_raises(ValueError, getitem, log, -1)

    # test iteration
    assert len(list(log)) == 2 
Example #3
Source File: test_bigmem.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def test_index_and_slice(self, size):
        t = (None,) * size
        self.assertEqual(len(t), size)
        self.assertEqual(t[-1], None)
        self.assertEqual(t[5], None)
        self.assertEqual(t[size - 1], None)
        self.assertRaises(IndexError, operator.getitem, t, size)
        self.assertEqual(t[:5], (None,) * 5)
        self.assertEqual(t[-5:], (None,) * 5)
        self.assertEqual(t[20:25], (None,) * 5)
        self.assertEqual(t[-25:-20], (None,) * 5)
        self.assertEqual(t[size - 5:], (None,) * 5)
        self.assertEqual(t[size - 5:size], (None,) * 5)
        self.assertEqual(t[size - 6:size - 2], (None,) * 4)
        self.assertEqual(t[size:size], ())
        self.assertEqual(t[size:size+5], ())

    # Like test_concat, split in two. 
Example #4
Source File: test_bigmem.py    From BinderFilter with MIT License 6 votes vote down vote up
def test_index_and_slice(self, size):
        t = (None,) * size
        self.assertEqual(len(t), size)
        self.assertEqual(t[-1], None)
        self.assertEqual(t[5], None)
        self.assertEqual(t[size - 1], None)
        self.assertRaises(IndexError, operator.getitem, t, size)
        self.assertEqual(t[:5], (None,) * 5)
        self.assertEqual(t[-5:], (None,) * 5)
        self.assertEqual(t[20:25], (None,) * 5)
        self.assertEqual(t[-25:-20], (None,) * 5)
        self.assertEqual(t[size - 5:], (None,) * 5)
        self.assertEqual(t[size - 5:size], (None,) * 5)
        self.assertEqual(t[size - 6:size - 2], (None,) * 4)
        self.assertEqual(t[size:size], ())
        self.assertEqual(t[size:size+5], ())

    # Like test_concat, split in two. 
Example #5
Source File: test_bigmem.py    From oss-ftp with MIT License 6 votes vote down vote up
def test_index_and_slice(self, size):
        t = (None,) * size
        self.assertEqual(len(t), size)
        self.assertEqual(t[-1], None)
        self.assertEqual(t[5], None)
        self.assertEqual(t[size - 1], None)
        self.assertRaises(IndexError, operator.getitem, t, size)
        self.assertEqual(t[:5], (None,) * 5)
        self.assertEqual(t[-5:], (None,) * 5)
        self.assertEqual(t[20:25], (None,) * 5)
        self.assertEqual(t[-25:-20], (None,) * 5)
        self.assertEqual(t[size - 5:], (None,) * 5)
        self.assertEqual(t[size - 5:size], (None,) * 5)
        self.assertEqual(t[size - 6:size - 2], (None,) * 4)
        self.assertEqual(t[size:size], ())
        self.assertEqual(t[size:size+5], ())

    # Like test_concat, split in two. 
Example #6
Source File: test_bigmem.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_index_and_slice(self, size):
        t = (None,) * size
        self.assertEqual(len(t), size)
        self.assertEqual(t[-1], None)
        self.assertEqual(t[5], None)
        self.assertEqual(t[size - 1], None)
        self.assertRaises(IndexError, operator.getitem, t, size)
        self.assertEqual(t[:5], (None,) * 5)
        self.assertEqual(t[-5:], (None,) * 5)
        self.assertEqual(t[20:25], (None,) * 5)
        self.assertEqual(t[-25:-20], (None,) * 5)
        self.assertEqual(t[size - 5:], (None,) * 5)
        self.assertEqual(t[size - 5:size], (None,) * 5)
        self.assertEqual(t[size - 6:size - 2], (None,) * 4)
        self.assertEqual(t[size:size], ())
        self.assertEqual(t[size:size+5], ())

    # Like test_concat, split in two. 
Example #7
Source File: test_utils.py    From dcos-kafka-service with Apache License 2.0 6 votes vote down vote up
def get_in(keys, coll, default=None):
    """ Reaches into nested associative data structures. Returns the value for path ``keys``.

    If the path doesn't exist returns ``default``.

    >>> transaction = {'name': 'Alice',
    ...                'purchase': {'items': ['Apple', 'Orange'],
    ...                             'costs': [0.50, 1.25]},
    ...                'credit card': '5555-1234-1234-1234'}
    >>> get_in(['purchase', 'items', 0], transaction)
    'Apple'
    >>> get_in(['name'], transaction)
    'Alice'
    >>> get_in(['purchase', 'total'], transaction)
    >>> get_in(['purchase', 'items', 'apple'], transaction)
    >>> get_in(['purchase', 'items', 10], transaction)
    >>> get_in(['purchase', 'total'], transaction, 0)
    0
    """
    try:
        return functools.reduce(operator.getitem, keys, coll)
    except (KeyError, IndexError, TypeError):
        return default 
Example #8
Source File: test_fakepwd.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_recordIndexable(self):
        """
        The shadow user record returned by I{getpwnam} and I{getspall} is
        indexable, with successive indexes starting from 0 corresponding to the
        values of the C{sp_nam}, C{sp_pwd}, C{sp_lstchg}, C{sp_min}, C{sp_max},
        C{sp_warn}, C{sp_inact}, C{sp_expire}, and C{sp_flag} attributes,
        respectively.
        """
        db = self.database
        (username, password, lastChange, min, max, warn, inact, expire,
         flag) = self.getExistingUserInfo()
        for entry in [db.getspnam(username), db.getspall()[0]]:
            self.assertEqual(entry[0], username)
            self.assertEqual(entry[1], password)
            self.assertEqual(entry[2], lastChange)
            self.assertEqual(entry[3], min)
            self.assertEqual(entry[4], max)
            self.assertEqual(entry[5], warn)
            self.assertEqual(entry[6], inact)
            self.assertEqual(entry[7], expire)
            self.assertEqual(entry[8], flag)

            self.assertEqual(len(entry), len(list(entry)))
            self.assertRaises(IndexError, getitem, entry, 9) 
Example #9
Source File: typing.py    From Imogen with MIT License 6 votes vote down vote up
def __reduce__(self):
        if self._special:
            return self._name

        if self._name:
            origin = globals()[self._name]
        else:
            origin = self.__origin__
        if (origin is Callable and
            not (len(self.__args__) == 2 and self.__args__[0] is Ellipsis)):
            args = list(self.__args__[:-1]), self.__args__[-1]
        else:
            args = tuple(self.__args__)
            if len(args) == 1 and not isinstance(args[0], tuple):
                args, = args
        return operator.getitem, (origin, args) 
Example #10
Source File: testutils.py    From pySINDy with MIT License 5 votes vote down vote up
def assert_equal_records(a, b):
    """
    Asserts that two records are equal.

    Pretty crude for now.

    """
    assert_equal(a.dtype, b.dtype)
    for f in a.dtype.names:
        (af, bf) = (operator.getitem(a, f), operator.getitem(b, f))
        if not (af is masked) and not (bf is masked):
            assert_equal(operator.getitem(a, f), operator.getitem(b, f))
    return 
Example #11
Source File: univ.py    From baidupan_shell with GNU General Public License v2.0 5 votes vote down vote up
def __getitem__(self, i):
        if isinstance(i, slice):
            return self.clone(
                operator.getitem(self._value, i)
                )
        else:
            return self._value[i] 
Example #12
Source File: test_dtype.py    From pySINDy with MIT License 5 votes vote down vote up
def test_fields_by_index(self):
        dt = np.dtype([('a', np.int8), ('b', np.float32, 3)])
        assert_dtype_equal(dt[0], np.dtype(np.int8))
        assert_dtype_equal(dt[1], np.dtype((np.float32, 3)))
        assert_dtype_equal(dt[-1], dt[1])
        assert_dtype_equal(dt[-2], dt[0])
        assert_raises(IndexError, lambda: dt[-3])

        assert_raises(TypeError, operator.getitem, dt, 3.0)
        assert_raises(TypeError, operator.getitem, dt, [])

        assert_equal(dt[1], dt[np.int8(1)]) 
Example #13
Source File: parse_dump.py    From isdi with MIT License 5 votes vote down vote up
def retrieve(dict_, nest):
    '''
    Navigates dictionaries like dict_[nest0][nest1][nest2]...
    gracefully.
    '''
    dict_ = dict_.to_dict() # for pandas
    try:
        return reduce(operator.getitem, nest, dict_)
    except KeyError as e:
        return ""
    except TypeError as e:
        return "" 
Example #14
Source File: univ.py    From baidupan_shell with GNU General Public License v2.0 5 votes vote down vote up
def __getitem__(self, i):
        if isinstance(i, slice):
            return self.clone(operator.getitem(self._value, i))
        else:
            return self._value[i] 
Example #15
Source File: pd_ios_apps.py    From isdi with MIT License 5 votes vote down vote up
def _retrieve(dict_, nest):
    '''
        Navigates dictionaries like dict_[nest0][nest1][nest2]...
        gracefully.
    '''
    dict_ = dict_.to_dict() # for pandas
    try:
        return reduce(operator.getitem, nest, dict_)
    except KeyError as e:
        return ""
    except TypeError as e:
        return "" 
Example #16
Source File: test_dtype.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 5 votes vote down vote up
def test_fields_by_index(self):
        dt = np.dtype([('a', np.int8), ('b', np.float32, 3)])
        assert_dtype_equal(dt[0], np.dtype(np.int8))
        assert_dtype_equal(dt[1], np.dtype((np.float32, 3)))
        assert_dtype_equal(dt[-1], dt[1])
        assert_dtype_equal(dt[-2], dt[0])
        assert_raises(IndexError, lambda: dt[-3])

        assert_raises(TypeError, operator.getitem, dt, 3.0)
        assert_raises(TypeError, operator.getitem, dt, [])

        assert_equal(dt[1], dt[np.int8(1)]) 
Example #17
Source File: univ.py    From aqua-monitor with GNU Lesser General Public License v3.0 5 votes vote down vote up
def __getitem__(self, i):
        if isinstance(i, slice):
            return self.clone(
                operator.getitem(self._value, i)
                )
        else:
            return self._value[i] 
Example #18
Source File: recovery.py    From astrobase with MIT License 5 votes vote down vote up
def _dict_get(datadict, keylist):
    return reduce(getitem, keylist, datadict) 
Example #19
Source File: univ.py    From aqua-monitor with GNU Lesser General Public License v3.0 5 votes vote down vote up
def __getitem__(self, i):
        if isinstance(i, slice):
            return self.clone(operator.getitem(self._value, i))
        else:
            return self._value[i] 
Example #20
Source File: univ.py    From aqua-monitor with GNU Lesser General Public License v3.0 5 votes vote down vote up
def __getitem__(self, i):
        if isinstance(i, slice):
            return self.clone(operator.getitem(self._value, i))
        else:
            return self._value[i] 
Example #21
Source File: tag.py    From aqua-monitor with GNU Lesser General Public License v3.0 5 votes vote down vote up
def __getitem__(self, idx):
        if isinstance(idx, slice):
            return self.__class__(
               self.__baseTag, *getitem(self.__superTags, idx)
            )
        return self.__superTags[idx] 
Example #22
Source File: github.py    From opencraft with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_extra_setting(self, name, default=None):
        """
        Return the setting given by "name" from extra_settings.

        The name may be a dot-separated path to retrieve nested settings.
        """
        extra_settings_dict = yaml.load(self.extra_settings, Loader=yaml.SafeLoader) or {}
        try:
            return functools.reduce(operator.getitem, name.split('.'), extra_settings_dict)
        except KeyError:
            return default 
Example #23
Source File: test_dtype.py    From GraphicDesignPatternByPython with MIT License 5 votes vote down vote up
def test_fields_by_index(self):
        dt = np.dtype([('a', np.int8), ('b', np.float32, 3)])
        assert_dtype_equal(dt[0], np.dtype(np.int8))
        assert_dtype_equal(dt[1], np.dtype((np.float32, 3)))
        assert_dtype_equal(dt[-1], dt[1])
        assert_dtype_equal(dt[-2], dt[0])
        assert_raises(IndexError, lambda: dt[-3])

        assert_raises(TypeError, operator.getitem, dt, 3.0)
        assert_raises(TypeError, operator.getitem, dt, [])

        assert_equal(dt[1], dt[np.int8(1)]) 
Example #24
Source File: testutils.py    From GraphicDesignPatternByPython with MIT License 5 votes vote down vote up
def assert_equal_records(a, b):
    """
    Asserts that two records are equal.

    Pretty crude for now.

    """
    assert_equal(a.dtype, b.dtype)
    for f in a.dtype.names:
        (af, bf) = (operator.getitem(a, f), operator.getitem(b, f))
        if not (af is masked) and not (bf is masked):
            assert_equal(operator.getitem(a, f), operator.getitem(b, f))
    return 
Example #25
Source File: later.py    From dplython with MIT License 5 votes vote down vote up
def evaluate(self, previousResult, original, **kwargs):
    return operator.getitem(previousResult, self.key) 
Example #26
Source File: get_value_from_yaml_in_tarball.py    From satellite-clone with GNU General Public License v3.0 5 votes vote down vote up
def get_value(data, keys):
    try:
        return reduce(operator.getitem, keys, data)
    except KeyError:
        return None 
Example #27
Source File: univ.py    From nzb-subliminal with GNU General Public License v3.0 5 votes vote down vote up
def __getitem__(self, i):
        if isinstance(i, slice):
            return self.clone(
                operator.getitem(self._value, i)
                )
        else:
            return self._value[i] 
Example #28
Source File: univ.py    From nzb-subliminal with GNU General Public License v3.0 5 votes vote down vote up
def __getitem__(self, i):
        if isinstance(i, slice):
            return self.clone(operator.getitem(self._value, i))
        else:
            return self._value[i] 
Example #29
Source File: univ.py    From nzb-subliminal with GNU General Public License v3.0 5 votes vote down vote up
def __getitem__(self, i):
        if isinstance(i, slice):
            return self.clone(operator.getitem(self._value, i))
        else:
            return self._value[i] 
Example #30
Source File: tag.py    From nzb-subliminal with GNU General Public License v3.0 5 votes vote down vote up
def __getitem__(self, idx):
        if isinstance(idx, slice):
            return self.__class__(
               self.__baseTag, *getitem(self.__superTags, idx)
            )
        return self.__superTags[idx]