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.
Post History
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 acce...
#4: Post edited
- Ignoring whether it's a good idea, there are a few mistakes in the implementation:
- - The magic method [`__getattr__`](https://docs.python.org/3/reference/datamodel.html#object.__getattr__) is called "when the default attribute access **fails**". To control _all_ attribute access, you want [`__getattribute__`](https://docs.python.org/3/reference/datamodel.html#object.__getattribute__).
- - By the same token, `super().__getattr__` is not defined.
- - [`__delete__`](https://docs.python.org/3/reference/datamodel.html#object.__delete__) is for descriptors only; that should be [`__delattr__`](https://docs.python.org/3/reference/datamodel.html#object.__delattr__).
- - Deletion methods (`__delattr__` and `__delete__`) don't return anything.
- And some surface-level things could be improved:
- - Pylint: "Unnecessary `else` after `return`; remove the `else` and de-indent the code inside it ([R1705:no-else-return](https://pylint.readthedocs.io/en/latest/user_guide/messages/refactor/no-else-return.html))". 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](https://pylint.readthedocs.io/en/latest/user_guide/messages/warning/raise-missing-from.html))". 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:"
- - `assert` is 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](https://peps.python.org/pep-0008/#blank-lines)
- - Add a `__repr__`! It's easy and helps a lot with debugging.
- ```
- class DictProxy:
# [docstring snipped for brevity]def __init__(self, dictionary):"""Initialize the DictProxy with a dictionary."""self._dictionary = dictionarydef __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 __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.]
- ```
- Ignoring whether it's a good idea, there are a few mistakes in the implementation:
- - The magic method [`__getattr__`](https://docs.python.org/3/reference/datamodel.html#object.__getattr__) is called "when the default attribute access **fails**". To control _all_ attribute access, you want [`__getattribute__`](https://docs.python.org/3/reference/datamodel.html#object.__getattribute__).
- - By the same token, `super().__getattr__` is not defined.
- - [`__delete__`](https://docs.python.org/3/reference/datamodel.html#object.__delete__) is for descriptors only; that should be [`__delattr__`](https://docs.python.org/3/reference/datamodel.html#object.__delattr__).
- - Deletion methods (`__delattr__` and `__delete__`) don't return anything.
- And some surface-level things could be improved:
- - Pylint: "Unnecessary `else` after `return`; remove the `else` and de-indent the code inside it ([R1705:no-else-return](https://pylint.readthedocs.io/en/latest/user_guide/messages/refactor/no-else-return.html))". 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](https://pylint.readthedocs.io/en/latest/user_guide/messages/warning/raise-missing-from.html))". 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:"
- - `assert` is 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](https://peps.python.org/pep-0008/#blank-lines)
- - 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.]
- ```
#3: Post edited
- Ignoring whether it's a good idea, there are a few mistakes in the implementation:
- - The magic method [`__getattr__`](https://docs.python.org/3/reference/datamodel.html#object.__getattr__) is called "when the default attribute access **fails**". To control _all_ attribute access, you want [`__getattribute__`](https://docs.python.org/3/reference/datamodel.html#object.__getattribute__).
- - By the same token, `super().__getattr__` is not defined.
- - [`__delete__`](https://docs.python.org/3/reference/datamodel.html#object.__delete__) is for descriptors only; that should be [`__delattr__`](https://docs.python.org/3/reference/datamodel.html#object.__delattr__).
- - Deletion methods (`__delattr__` and `__delete__`) don't return anything.
- And some surface-level things could be improved:
- - Pylint: "Unnecessary `else` after `return`; remove the `else` and de-indent the code inside it ([R1705:no-else-return](https://pylint.readthedocs.io/en/latest/user_guide/messages/refactor/no-else-return.html))". 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](https://pylint.readthedocs.io/en/latest/user_guide/messages/warning/raise-missing-from.html))". 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:"
- - `assert` is 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](https://peps.python.org/pep-0008/#blank-lines)
- - Add a `__repr__`! It's easy and helps a lot with debugging.
- ```
- class DictProxy:
- # [docstring snipped for brevity]
- 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 __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.]
```[]()[]()[]()
- Ignoring whether it's a good idea, there are a few mistakes in the implementation:
- - The magic method [`__getattr__`](https://docs.python.org/3/reference/datamodel.html#object.__getattr__) is called "when the default attribute access **fails**". To control _all_ attribute access, you want [`__getattribute__`](https://docs.python.org/3/reference/datamodel.html#object.__getattribute__).
- - By the same token, `super().__getattr__` is not defined.
- - [`__delete__`](https://docs.python.org/3/reference/datamodel.html#object.__delete__) is for descriptors only; that should be [`__delattr__`](https://docs.python.org/3/reference/datamodel.html#object.__delattr__).
- - Deletion methods (`__delattr__` and `__delete__`) don't return anything.
- And some surface-level things could be improved:
- - Pylint: "Unnecessary `else` after `return`; remove the `else` and de-indent the code inside it ([R1705:no-else-return](https://pylint.readthedocs.io/en/latest/user_guide/messages/refactor/no-else-return.html))". 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](https://pylint.readthedocs.io/en/latest/user_guide/messages/warning/raise-missing-from.html))". 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:"
- - `assert` is 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](https://peps.python.org/pep-0008/#blank-lines)
- - Add a `__repr__`! It's easy and helps a lot with debugging.
- ```
- class DictProxy:
- # [docstring snipped for brevity]
- 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 __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.]
- ```
#2: Post edited
- Ignoring whether it's a good idea, there are a few mistakes in the implementation:
- [`__getattr__`](https://docs.python.org/3/reference/datamodel.html#object.__getattr__) is called "when the default attribute access **fails**". To control _all_ attribute access, you want [`__getattribute__`](https://docs.python.org/3/reference/datamodel.html#object.__getattribute__).- - By the same token, `super().__getattr__` is not defined.
- - [`__delete__`](https://docs.python.org/3/reference/datamodel.html#object.__delete__) is for descriptors only; that should be [`__delattr__`](https://docs.python.org/3/reference/datamodel.html#object.__delattr__).
- - Deletion methods (`__delattr__` and `__delete__`) don't return anything.
- And some surface-level things could be improved:
- - Pylint: "Unnecessary `else` after `return`; remove the `else` and de-indent the code inside it ([R1705:no-else-return](https://pylint.readthedocs.io/en/latest/user_guide/messages/refactor/no-else-return.html))". 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](https://pylint.readthedocs.io/en/latest/user_guide/messages/warning/raise-missing-from.html))". 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:"
- - `assert` is 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](https://peps.python.org/pep-0008/#blank-lines)
- - Add a `__repr__`! It's easy and helps a lot with debugging.
- ```
- class DictProxy:
- # [docstring snipped for brevity]
- 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 __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.]
```
- Ignoring whether it's a good idea, there are a few mistakes in the implementation:
- - The magic method [`__getattr__`](https://docs.python.org/3/reference/datamodel.html#object.__getattr__) is called "when the default attribute access **fails**". To control _all_ attribute access, you want [`__getattribute__`](https://docs.python.org/3/reference/datamodel.html#object.__getattribute__).
- - By the same token, `super().__getattr__` is not defined.
- - [`__delete__`](https://docs.python.org/3/reference/datamodel.html#object.__delete__) is for descriptors only; that should be [`__delattr__`](https://docs.python.org/3/reference/datamodel.html#object.__delattr__).
- - Deletion methods (`__delattr__` and `__delete__`) don't return anything.
- And some surface-level things could be improved:
- - Pylint: "Unnecessary `else` after `return`; remove the `else` and de-indent the code inside it ([R1705:no-else-return](https://pylint.readthedocs.io/en/latest/user_guide/messages/refactor/no-else-return.html))". 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](https://pylint.readthedocs.io/en/latest/user_guide/messages/warning/raise-missing-from.html))". 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:"
- - `assert` is 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](https://peps.python.org/pep-0008/#blank-lines)
- - Add a `__repr__`! It's easy and helps a lot with debugging.
- ```
- class DictProxy:
- # [docstring snipped for brevity]
- 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 __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.]
- ```[]()[]()[]()
#1: Initial revision
Ignoring whether it's a good idea, there are a few mistakes in the implementation:
- [`__getattr__`](https://docs.python.org/3/reference/datamodel.html#object.__getattr__) is called "when the default attribute access **fails**". To control _all_ attribute access, you want [`__getattribute__`](https://docs.python.org/3/reference/datamodel.html#object.__getattribute__).
- By the same token, `super().__getattr__` is not defined.
- [`__delete__`](https://docs.python.org/3/reference/datamodel.html#object.__delete__) is for descriptors only; that should be [`__delattr__`](https://docs.python.org/3/reference/datamodel.html#object.__delattr__).
- Deletion methods (`__delattr__` and `__delete__`) don't return anything.
And some surface-level things could be improved:
- Pylint: "Unnecessary `else` after `return`; remove the `else` and de-indent the code inside it ([R1705:no-else-return](https://pylint.readthedocs.io/en/latest/user_guide/messages/refactor/no-else-return.html))". 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](https://pylint.readthedocs.io/en/latest/user_guide/messages/warning/raise-missing-from.html))". 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:"
- `assert` is 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](https://peps.python.org/pep-0008/#blank-lines)
- Add a `__repr__`! It's easy and helps a lot with debugging.
```
class DictProxy:
# [docstring snipped for brevity]
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 __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.]
```
