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

Read Only version #74

Closed
zee-sh opened this issue Nov 23, 2016 · 5 comments
Closed

Read Only version #74

zee-sh opened this issue Nov 23, 2016 · 5 comments

Comments

@zee-sh
Copy link

zee-sh commented Nov 23, 2016

How can I make this read-only and when you try to add an attribute it will raise an exception, something like a Frozen Addict.

Also why does this create an empty dict on when trying to access an attribute that does not exist. It should raise an exception unless you are setting an attribute that does not exist

@Ohjeah
Copy link
Contributor

Ohjeah commented Nov 23, 2016

Had the same issue.
This works for me:

https://gist.github.com/Ohjeah/41b103e4bc15452af5bbc89747962369

@mewwts
Copy link
Owner

mewwts commented Nov 23, 2016

Hey!

Unfortunately, it's (afaik) not possible to get addicts functionality without creating an empty dictionary on lookup. Essentially, when you do my_dict.a.b = 2, Python first tries to figure out what my_dict.a.b is. If my_dict.a does not exist when __getattr__ is called on my_dict, Python will raise an exception. Hence, as a workaround, and tbh this is the whole idea that makes addict work, we return a empty dictionary, so that when the __setattr__ is called on my_dict.a we're able to do set the item in my_dict.

If I'm not misunderstanding the question you could always call .to_dict() in order to transform it into a regular python dict, and disallow further __setattr__.

Cheers,

Mats

@Ohjeah
Copy link
Contributor

Ohjeah commented Nov 23, 2016

If you just use .to_dict() you will lose the dot-access to dict items too!

@mewwts
Copy link
Owner

mewwts commented Nov 23, 2016

That's true @Ohjeah.

@Ohjeah
Copy link
Contributor

Ohjeah commented Nov 23, 2016

Hence the LockedDict (see the gist). It serves as a read only version of addict.Dict. Works well for me if I want an exception rather a None value return on a failed item lookup.

@mewwts mewwts closed this as completed Dec 12, 2016
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

3 participants