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

Use Dot String to Access DotMap Paths #57

Open
awagneratzendesk opened this issue Dec 31, 2019 · 4 comments
Open

Use Dot String to Access DotMap Paths #57

awagneratzendesk opened this issue Dec 31, 2019 · 4 comments

Comments

@awagneratzendesk
Copy link

awagneratzendesk commented Dec 31, 2019

I have a piece of software that outputs dictionary mapping in dot notation. I was hoping to be able to assign the dot notation to a variable and pass it to a DotMap for a lookup but that does not seem possible.

mydict = {
  "my": {
      "dot": {
        "notation": 1
      }
    }
}
m = DotMap(mydict)
my_dotnotation = "my.dot.notation"

print(m.lookup(my_dotnotation)

I would expect that code to print "1". Just noting this down here as a nice to have given that it looks like that is what #27 was also looking for.

https://github.com/cdgriffith/Box#box-dots actually looks to have that functionality.

@tsai0009
Copy link

Also setting a dictionary value will not work.

ie. you cannot do this:

x = blah.blah.blah
m.x = "test"

it would translate to:

{"x": "test")

and not:

{"blah": {"blah": {"blah": "test"}}}

@drgrib drgrib changed the title Using a String to Access DotMap Paths Using Dot String to Access DotMap Paths Jan 26, 2020
@drgrib drgrib changed the title Using Dot String to Access DotMap Paths Use Dot String to Access DotMap Paths Jan 26, 2020
@drgrib
Copy link
Owner

drgrib commented Jan 26, 2020

I don't use Python enough anymore to justify the amount of effort it would take me to implement this. Almost all of my personal development is in Go now.

You are welcome to create a PR that adds the feature and doesn't break the unit tests (or appropriately modifies them) and adds a flag to disable it with DotMap(_dotStringAccess=False).

@ocervell
Copy link

@drgrib it wouldn't be that hard IMO (but very useful).

Something like this should do:

def lookup(self, path):
    dotted_path = path.split(".")
    current = self
    for piece in dotted_path:
         current = getattr(current, piece)
    return current

The hard part would be to be able to rewrite getattr so that getattr(dotmap_dict, 'a.b.c.d') works, but the solution above would be a pretty good temp solution.

@beoboo
Copy link

beoboo commented Apr 6, 2020

This should be doable with something like this: https://vinta.ws/code/dot-notation-obj-x-y-z-for-nested-objects-and-dictionaries-in-python.html

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

No branches or pull requests

6 participants