Git Product home page Git Product logo

Comments (4)

mahmoud avatar mahmoud commented on May 21, 2024

remap is just letting you know that with that enter, absolutely no remapping would occur. If the very first enter returns False, it's like passing an object that isn't iterable. I can look at improving the error message, perhaps?

from boltons.

grundic avatar grundic commented on May 21, 2024

Maybe the error message could be improved, but I don't know how to formulate it better :-/
How then I would avoid entering some items? Does this looks good from your point of view:

def enter(path, key, value):
    # I'd like to skip `baz's`
    if 'baz' in value and isinstance(value, dict):
        value.pop('baz')
    return default_enter(path, key, value)

print(remap({'foo': 'bar', 'baz': 'qux', 'data': ['foo', 'bar', 'baz']}, enter=enter))

>>> {'foo': 'bar', 'data': ['foo', 'bar', 'baz']}

Originally my problem is next: I have a nested dictionaries, which represents hierarchical configuration object. All children should inherit parent properties, they can append to them or override them. And what I need is to transpose this hierarchical structure, so I can ask each node about its properties taking into account parent properties.
Again, here is an example of my current implementation:

import copy

d = {
    'name': 'ROOT',
    'properties': ['foo'],
    'includes': [
        {
            'name': 'nested-1',
            'properties-override': ['bar', 'baz'],
            'includes': [
                {'id': '1'},
                {'id': '2', 'properties': ['quz']},
                {'id': '3'},
            ]
        }
    ]
}


def traverse(data, parents=None):
    result = list()

    if parents is None:
        parents = list()

    if 'id' in data:
        assert 'includes' not in data
        data['parents'] = copy.deepcopy(parents)
        return [data]
    else:
        includes = data.pop('includes', list())
        parents.append(data)

        if not isinstance(includes, list):
            includes = [includes]

        for inc in includes:
            child = traverse(inc, parents)
            result.extend(child)

        parents.pop()
    return result


if __name__ == '__main__':
    for item in traverse(d):
        print(item)

>>> {'id': '1', 'parents': [{'name': 'ROOT', 'properties': ['foo']}, {'properties-override': ['bar', 'baz'], 'name': 'nested-1'}]}
>>> {'id': '2', 'properties': ['quz'], 'parents': [{'name': 'ROOT', 'properties': ['foo']}, {'properties-override': ['bar', 'baz'], 'name': 'nested-1'}]}
>>> {'id': '3', 'parents': [{'name': 'ROOT', 'properties': ['foo']}, {'properties-override': ['bar', 'baz'], 'name': 'nested-1'}]}

Can the same problem be solved with remap functionality?
Sorry, maybe that's too big/complex question for the ticket.

from boltons.

grundic avatar grundic commented on May 21, 2024

Okay, looks like I implemented the same traverse method with remap functionality, but I don't know whether it's optimal or not:

import copy
from boltons.iterutils import remap, default_enter, default_exit

d = {
    'name': 'ROOT',
    'properties': ['foo'],
    'includes': [
        {
            'name': 'nested-1',
            'properties-override': ['bar', 'baz'],
            'includes': [
                {'id': '1'},
                {'id': '2', 'properties': ['quz']},
                {'id': '3'},
            ]
        }
    ]
}


def traverse(data=None):
    if not data:
        data = d

    result = list()
    parents = list()

    def enter(path, key, value):
        if 'includes' in value:
            includes = value.pop('includes')
            parents.append(value)
            value = includes

        res = default_enter(path, key, value)
        return res

    def visit(path, key, value):
        if 'id' in value and isinstance(value, dict):
            item = copy.deepcopy(value)
            item['parents'] = copy.deepcopy(parents)
            result.append(item)

        return key, value

    def exit(path, key, old_parent, new_parent, new_items):
        if old_parent == parents[-1]:
            parents.pop()
        res = default_exit(path, key, old_parent, new_parent, new_items)
        return res

    remap(data, visit=visit, enter=enter, exit=exit)
    return result


if __name__ == '__main__':
    for item in traverse(d):
        print(item)

>>> {'id': '1', 'parents': [{'name': 'ROOT', 'properties': ['foo']}, {'properties-override': ['bar', 'baz'], 'name': 'nested-1'}]}
>>> {'id': '2', 'properties': ['quz'], 'parents': [{'name': 'ROOT', 'properties': ['foo']}, {'properties-override': ['bar', 'baz'], 'name': 'nested-1'}]}
>>> {'id': '3', 'parents': [{'name': 'ROOT', 'properties': ['foo']}, {'properties-override': ['bar', 'baz'], 'name': 'nested-1'}]}

from boltons.

grundic avatar grundic commented on May 21, 2024

Ah, it's still not perfect, but won't bother you with opened ticket.
Thank you :)

from boltons.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.