Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

AttrDict doesn't handle list properly #35

Open
anton-tagunov opened this issue Sep 6, 2013 · 0 comments
Open

AttrDict doesn't handle list properly #35

anton-tagunov opened this issue Sep 6, 2013 · 0 comments

Comments

@anton-tagunov
Copy link

Example:

        d = AttrDict({"a": 1, "b": 2, "c": {"d": 3, "e": [4, 5, {"f": 6, "g": 7}]}})
        self.assertEqual(d.c.e[2].f, 6) # AttributeError: 'dict' object has no attribute 'f'

I suggest to change AttrDict.setitem:

    def __convert_value__(self, value):
        if isinstance(value, dict):
            return AttrDict(value)
        elif isinstance(value, (list, tuple)):
            return [self.__convert_value__(v) for v in value]
        return value

    def __setitem__(self, key, value):
        # Coerce all nested dict-valued fields into AttrDicts
        return super(AttrDict, self).__setitem__(key, self.__convert_value__(value))



My tests:
    def test_attrdict(self):
        d = AttrDict({"a": 1, "b": 2, "c": {"d": 3, "e": [4, 5, {"f": 6, "g": 7}]}})
        self.assertEqual(d.a, 1)
        self.assertEqual(d.b, 2)
        self.assertEqual(d.c.d, 3)
        self.assertEqual(d.c.e[2].f, 6)
        self.assertEqual(d.c.e[2].g, 7)

        with self.assertRaises(AttributeError):
            a = d.qq


        d = AttrDict({"c": [{"f": 6, "g": 7}, [{"a": 1}]]})
        self.assertEqual(d.c[1][0], 1)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant