Skip to content

Commit

Permalink
Add support for __getattr__ (clarete#36)
Browse files Browse the repository at this point in the history
  • Loading branch information
stevenfontanella committed Nov 19, 2019
1 parent a282725 commit 3420ac8
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 0 deletions.
2 changes: 2 additions & 0 deletions forbiddenfruit/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,7 @@ class PyAsyncMethods(ctypes.Structure):
('tp_hash', ctypes.CFUNCTYPE(ctypes.c_int64, PyObject_p)),
('tp_call', ctypes.CFUNCTYPE(PyObject_p, PyObject_p, PyObject_p, PyObject_p)),
('tp_str', ctypes.CFUNCTYPE(PyObject_p, PyObject_p)),
('tp_getattr', ctypes.CFUNCTYPE(PyObject_p, PyObject_p, PyObject_p))
# ...
]

Expand Down Expand Up @@ -317,6 +318,7 @@ def __filtered_dir__(obj=None):
# divmod isn't a dunder, still make it overridable
override_dict['divmod()'] = ('tp_as_number', "nb_divmod")
override_dict['__str__'] = ('tp_str', "tp_str")
override_dict['__getattr__'] = ('tp_getattr', "tp_getattr")


def _is_dunder(func_name):
Expand Down
13 changes: 13 additions & 0 deletions tests/unit/test_forbidden_fruit.py
Original file line number Diff line number Diff line change
Expand Up @@ -330,3 +330,16 @@ def type_error_str(self):

reverse(TypeError, '__str__')
assert str(te) == "testing"

@skip_legacy
def test_overriding_getattr():
"""Overload __getattr__ for dicts to lookup a key"""
def getter(self, x):
try:
return object.__getattribute__(self, x)
except AttributeError:
return self[x]
curse(dict, "__getattr__", getter)

my_dict = {"abc": "xyz"}
assert(my_dict.abc == "xyz")

0 comments on commit 3420ac8

Please sign in to comment.