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

Add support for __getattr__ (#36) #37

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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")