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.
A class to access dicts using attribute syntax
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:
-
Is this class a good idea to begin with?
-
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()
4 answers
I like the idea, but more as an exercise or a demonstration what can be done with Python. I also like that the code comes with a set of test cases which are written in a way that they nicely serve as user documentation. In fact, I could even imagine this example being used in a tutorial about the __setattr__ etc. methods.
However, unless there is a real use-case where such a feature is needed for some reason, I would rather not start using it only for the syntactic difference: For readers of code, such tricks increase the cognitive complexity.
Having one idiomatic way of doing something makes things easier in most cases (https://peps.python.org/pep-0020):
There should be one -- and preferably only one -- obvious way to do it.
0 comment threads
The following users marked this post as Works for me:
| User | Comment | Date |
|---|---|---|
| celtschk | (no comment) | Apr 14, 2022 at 03:56 |
-
It is useful sometimes, for example consider a program accepting input in the form of templates. An input of
"Value: {obj.field}"is more readable than"Value: {obj['field']}".- Such an example is an app processing JSON and evaluating expressions on it, like
jqor a similar Python app,pjy:pjy d.item.subiteminstead ofpjy "d['item']['subitem']"
- Such an example is an app processing JSON and evaluating expressions on it, like
-
There are other ways to do it:
- Subclass dict and implement
def __getattr__(self, attr): return self[attr] - Use
self.__dict__instead ofself._dictionary
- Subclass dict and implement
0 comment threads
Ignoring whether it's a good idea, there are a few mistakes in the implementation:
- The magic method
__getattr__is called "when the default attribute access fails". To control all attribute access, you want__getattribute__.- By the same token,
super().__getattr__is not defined.
- By the same token,
-
__delete__is for descriptors only; that should be__delattr__. - Deletion methods (
__delattr__and__delete__) don't return anything.
And some surface-level things could be improved:
- Pylint: "Unnecessary
elseafterreturn; remove theelseand de-indent the code inside it (R1705:no-else-return)". In effect, convert your if-else's to guard statements. - Pylint: "Consider explicitly re-raising using
raise AttributeError(error) from error(W0707:raise-missing-from)". This changes part of the error message from "During handling of the above exception, another exception occurred:" to "The above exception was the direct cause of the following exception:" -
assertis a statement, not a function, so the parentheses are not needed and can be confusing - Methods should be separated by 1 newline, not 2, per PEP 8
- Add a
__repr__! It's easy and helps a lot with debugging.
class DictProxy:
# [snip]
def __getattribute__(self, name):
"""
Redirect non-underscore attribute reads to dictionary reads
"""
if name[0] == "_":
return super().__getattribute__(name)
try:
return self._dictionary[name]
except KeyError as error:
# hasattr fails if the exception isn't an AttributeError
raise AttributeError(error) from error
def __delattr__(self, name):
"""
Redirect non-underscore attribute deletes to dictionary deletes
"""
if name[0] == "_":
super().__delattr__(name)
else:
del self._dictionary[name]
def __repr__(self):
"""Show construction."""
clsname = type(self).__name__
return f'{clsname}({self._dictionary!r})'
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")
# [etc.]
0 comment threads
I've used something similar in the past (supporting attribute access as equivalent to dict item access), but I would then always derive the class from dict (or UserDict). This can be useful - but mainly inside your own code, never as library code - if you have sections of the code that otherwise would need a lot of quoting plus square brackets.
It's tricky code, and I'd generally advise not to use it however:
- If a dictionary is passed in as argument to the class init, then after constructing the object, you have two, entirely separate references to a mutable dict in your code. This easily allows bugs to crawl in. It seems better to derive the class from dict or UserDict to prevent this.
- "DictProxy" seems a somewhat misleading or confusing name since it's not really a dict proxy: it doesn't add behavior to a class that otherwise behaves like a dict. It's also a bit confusing because the stdlib has various abc.mapping classes (and types.MappingProxy). I think this is yet another reason why it may be better to derive the class from collections.UserDict (or do sth similar).
- If the class is merely intended as view on the underlying dict data, I would make sure that instances of it are immutable (derive the class from Mapping or MappingView for instance).
- There seems to be an implicit assumption that the underlying dict will not have keys that are not valid Python attribute identifiers. This assumption could also lead to trouble (since certain keys will not be representable as attributes).

1 comment thread