Communities

Writing
Writing
Codidact Meta
Codidact Meta
The Great Outdoors
The Great Outdoors
Photography & Video
Photography & Video
Scientific Speculation
Scientific Speculation
Cooking
Cooking
Electrical Engineering
Electrical Engineering
Judaism
Judaism
Languages & Linguistics
Languages & Linguistics
Software Development
Software Development
Mathematics
Mathematics
Christianity
Christianity
Code Golf
Code Golf
Music
Music
Physics
Physics
Linux Systems
Linux Systems
Power Users
Power Users
Tabletop RPGs
Tabletop RPGs
Community Proposals
Community Proposals
tag:snake search within a tag
answers:0 unanswered questions
user:xxxx search by author id
score:0.5 posts with 0.5+ score
"snake oil" exact phrase
votes:4 posts with 4+ votes
created:<1w created < 1 week ago
post_type:xxxx type of post
Search help
Notifications
Mark all as read See all your notifications »
Code Reviews

Welcome to Software Development on Codidact!

Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.

Comments on A class to access dicts using attribute syntax

Post

A class to access dicts using attribute syntax

+4
−0

I've written a class that allows to access dictionary entries of arbitrary dicts with appropriate string keys through attribute access syntax on an instance of the class.

My questions are:

  1. Is this class a good idea to begin with?

  2. Is there anything that should be done differently?

Here's the class:

class DictProxy: 
    """
    Allow to access a dictionary through attribute access syntax.

    Obviously only dictionary entries whose keys are strings
    conforming to identifier rules can be accessed this way; also,
    identifiers starting with underscore are not delegated to the
    dictionary (thus dictionary entries whose key starts with
    underscore cannot be accessed this way).
    """

    def __init__(self, dictionary):
        """
        Initialize the DictProxy with a dictionary
        """
        self._dictionary = dictionary


    def __setattr__(self, name, value):
        """
        Redirect non-underscore attribute assignments to dictionary updates
        """
        if name[0] == "_":
            super().__setattr__(name, value)
        else:
            self._dictionary[name] = value


    def __getattr__(self, name):
        """
        Redirect non-underscore attribute reads to dictionary reads
        """
        if name[0] == "_":
            return super().__getattr__(name)
        else:
            try:
                return self._dictionary[name]
            except KeyError as error:
                # hasattr fails if the exception isn't an AttributeError
                raise AttributeError(error)


    def __delattr__(self, name):
        """
        Redirect non-underscore attribute deletes to dictionary deletes
        """
        # the actual code
        if name[0] == "_":
            return super().__delete__(name)
        else:
            del self._dictionary[name]


def test():
    dictionary = { "a": 1, "b": 2, "c": 3 }
    proxy = DictProxy(dictionary)

    assert(hasattr(proxy, "a"))
    assert(hasattr(proxy, "b"))
    assert(hasattr(proxy, "c"))
    assert(not hasattr(proxy, "d"))

    assert(proxy.a == 1)
    assert(proxy.b == 2)
    assert(proxy.c == 3)

    proxy.a = 4

    assert(proxy.a == 4)
    assert(dictionary["a"] == 4)

    proxy.d = 5

    assert(hasattr(proxy, "d"))
    assert(proxy.d == 5)
    assert("d" in dictionary)
    assert(dictionary["d"] == 5)

    del proxy.a

    assert(not hasattr(proxy, "a"))
    assert(not "a" in dictionary)

    delattr(proxy, "b")

    assert(not hasattr(proxy, "b"))
    assert(not "b" in dictionary)

    dictionary["a"] = 6

    assert(hasattr(proxy, "a"))
    assert(proxy.a == 6)

    del dictionary["c"]

    assert(not hasattr(proxy, "c"))


if __name__ == '__main__':
    test()
History
Why does this post require attention from curators or moderators?
You might want to add some details to your flag.
Why should this post be closed?

1 comment thread

If that's a good idea, it depends on what you need. Is this functionality (syntatic sugar) worth t... (5 comments)
If that's a good idea, it depends on what you need. Is this functionality (syntatic sugar) worth t...
hkotsubo‭ wrote about 3 years ago

If that's a good idea, it depends on what you need.

Is this functionality (syntatic sugar) worth the overhead of having an additional class for each dictionary you want to wrap? It's hard to tell without knowing the requirements and/or motivations to have such class (it's only syntatic sugar/"terse" code?)

Not to mention that this wrapper doesn't have all the other dict functionalities, such as methods (values(), items(), etc), can't be iterated, can't get its len, etc (although it's possible - and relatively easy - to implement them). Not sure if that's the intention, though.

celtschk‭ wrote about 3 years ago

An additional class for each dictionary? You didn't actually read my code, did you?

But yes, the goal is syntactic sugar. Being able to use proxy.foo instead of dictionary["foo"].

hkotsubo‭ wrote about 3 years ago

Sorry, I meant "additional instance for each dictionary".

celtschk‭ wrote about 3 years ago

Well, for each dictionary that you want to access this way. And an instance is cheap, isn't it? However thinking of it, one useful addition would be to recursively treat dictionary values (possibly controlled by a constructor option), by automatically wrapping them as well if accessed as attributes.

hkotsubo‭ wrote about 3 years ago

Whether is cheap or not, it depends. If you think it is, then go for it :-)

Just reminding that it's not only one instance, there's also the cost of an extra method call every time you get/set/delete an attribute. If that's not a concern, and you think is worth the convenience of having the syntatic sugar, I don't see a reason to not use it.