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

Add Attr based access #18

Open
rodfersou opened this issue Oct 28, 2024 · 0 comments
Open

Add Attr based access #18

rodfersou opened this issue Oct 28, 2024 · 0 comments

Comments

@rodfersou
Copy link

rodfersou commented Oct 28, 2024

https://code.activestate.com/recipes/578644-wrist-friendly-dictionary/

class easyaccessdict(dict):
    def __getattr__(self, name):
        return self[name]
    def __setattr__(self, name, value):
        super().__setitem__(name,value)
    def __missing__(self, name):
        super().__setitem__(name, easyaccessdict())
        return super().__getitem__(name)
>>> d= easyaccessdict()
>>> d
{}
>>> d.foo.bar= 'a'
>>> d
{'foo':{'bar':'a'}}
>>> d['foo']
{'bar':'a'}
>>> d['foo'].blah= 7
>>> d
{'foo':{'bar':'a', 'blah':7}}
>>> d.a.b.c.e.e.f.g.h= 11

Also I have a use case where would be good to accept the dot syntax in the dict:

>>> from path_dict import PathDict
>>> d = PathDict({})
>>> d['a.b.c.d'] = 2
>>> print(dict(d))
{'a.b.c.d': 2}

This is my current workaround:

>>> from path_dict import PathDict
>>> d = PathDict({})
>>> d[*'a.b.c.d'.split('.')] = 2
>>> print(dict(d))
{'a': {'b': {'c': {'d': 2}}}}

A small change here would fix the issue:

before:

	def __getitem__(self, path):
		at = self.at(*path) if isinstance(path, tuple) else self.at(path)
		if isinstance(at, MultiPathDict):
			return at.gather()
		res = at.get()
		self.at_root()
		return res

after:

	def __getitem__(self, path):
                if isinstance(path, str):
                    path = path.split('.')
		at = self.at(*path) if isinstance(path, tuple) else self.at(path)
		if isinstance(at, MultiPathDict):
			return at.gather()
		res = at.get()
		self.at_root()
		return res

same goes to __set__

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