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
PyObject_GenericGetAttr suppresses AttributeErrors in descriptors #45956
Comments
it seems the code of PyObject_GenericGetAttr, which invokes the the attached example is quite artificial, but it's a simplification of this bug only happens when the class defines a custom __getattr__. see |
I can confirm that with SVN trunk, and it's actually even worse because >>> class Foo(object):
... def __getattr__(self, name): return 42
... @property
... def bacon(self): return int.lalala
...
>>> f = Foo()
>>> f.bacon
42
>>> Foo.bacon.__get__(f)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 4, in bacon
AttributeError: type object 'int' has no attribute 'lalala' |
PyObject_GenericGetAttr is invoked from slot_tp_getattr_hook in |
here's a short example of the bug >>> class Foo(object):
... def __getattr__(self, name):
... return 42
... @property
... def bacon(self):
... return int.lalala
... @property
... def eggs(self):
... return 17
...
>>> f = Foo()
>>> f.bacon # raises an AttributeError, and silently ignores it
42
>>> f.eggs
17
>>> are there any news in this front? |
Related reading from a few years back: http://coding.derkeiler.com/Archive/Python/comp.lang.python/2005-05/msg03829.html |
This is still an issue with the latest trunk. |
I consider this to be a feature. Properties can raise AttributeError to defer to __getattr__. |
I ran into this recently, as well, and have lost probably a day's worth of time debugging it. I submit that this is not a feature - I can't imagine a real-world scenario where you actually want to write debuggable code where a descriptor defers to __getattr__ (except perhaps for exception handling, in which case some re-factoring is in order), particularly because descriptors are effectively mix-ins and can be used on multiple classes. I worked around this by writing an ancestor descriptor that catches AttributeErrors and re-raises them as a user-defined exception. |
Got bit by a variation of this today in 2.7: class Spam(object):
def __getattr__(self, attr):
raise AttributeError(attr)
@property
def eggs(self):
return self.ham
s = Spam()
s.eggs
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in __getattr__
AttributeError: eggs It took me a little while to figure out what was going on. A real head-scratcher. This is because the AttributeError was attributed to the property, but was actually caused by the __getattr__ call triggered by the property's code. I would expect the AttributeError to reference "ham", not "eggs". As already noted, if __getattr__() is not there, that's what happens. Regardless, I'm just not seeing where the hurdle is to improving this behavior. I certainly agree that this is not a feature. It is the source of very mysterious failures. I was surprised that AttributeError does not have an attribute to which the name would be bound. If it did, then slot_tp_getattr_hook() could check against that: if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
PyObject *tp, *exc, *tb, *exc_attr;
PyErr_Fetch(&tp, &exc, &tb);
exc_attr = PyObject_GetAttrString(exc, "attribute");
PyErr_Restore(tp, exc, tb);
if (!exc_attr || exc_attr == name) {
PyErr_Clear();
res = call_attribute(self, getattr, name);
}
Py_XDECREF(exc_attr);
} Alternatively, when an AttributeError comes out of a getter in _PyObject_GenericSetAttrWithDict() (in either spot they're called), another exception (not AttributeError) could be raised with the original chained onto it. Then slot_tp_getattr_hook() won't silently ignore it. It would be something like this: if (f != NULL && PyDescr_IsData(descr)) {
res = f(descr, obj, value);
if (!res && PyErr_ExceptionMatches(PyExc_AttributeError)) {
PyObject *msg = PyUnicode_FromFormat("getter failed for '%U'", name);
/* implicit chaining here */
PyErr_SetObject(PyExc_???Error, msg);
}
goto done;
} Conceptually, it's as though locating the attribute and extracting the value are lumped together here. Distinguishing the two would help make this failure situation much less confusing. Additionally, it would be really helpful to have a brief mention of this behavior (AttributeErrors in getters falling back to __getattr__) in the language reference entry for __getattr__ and/or descriptors. |
The whole AttributeError gaining an attribute seems impractical, but the second approach still seems reasonable to me. I've attached a rough patch to demonstrate. If that looks okay, I can flesh it out. |
Benjamin Peterson added the comment:
Micah Friesen added the comment:
No need to imagine. The new Enum class uses this ability to support having both protected properties on enum members and enum members of the same name: --> from enum import Enum Enum's custom __getattr__ is located in the metaclass, however, not in the class. For future reference, here is a short test script and it's output in 3.4.0a2+: class WithOut:
@property
def huh(self):
return self.not_here
class With:
@property
def huh(self):
return self.not_here
def __getattr__(self, name):
print('looking up %s' % name)
raise AttributeError('%s not in class %s' % (name, type(self))) try: print()
try:
With().huh
except AttributeError as exc:
print(exc)
print()
import enum # broken value property tries to access self.not_here
class TestEnum(enum.Enum):
one = 1
print(TestEnum.one.value) ===================================================================================== looking up not_here meta getattr with __new_member__ |
Marking this for Python 3.4. It isn't a bug in the descriptor protocol; rather, it is an implementation detail that is sometimes helpful but is mostly annoying. |
Well, attached patch doesn't segfault in debug mode, but the errors aren't any better; in fact, I'd say their worse. Here's the current output from my test script: =============================================================== looking up not_here Traceback (most recent call last):
File "break_getattr.py", line 30, in <module>
print(TestEnum.one.missing)
AttributeError: getter failed for descriptor 'missing' =============================================================== As you can see, we have even less information when a class level __getattr__ is /absent/, and when we do have one, there is no change (which is exactly where we really wanted the change). :( |
If anyone with more experience wants ownership, feel free to take it from me. ;) Otherwise I'll do my best to get this figured out in time for the beta. |
Results from the first two tests in my test script: looking up not_here |
Downside to this patch (stoneleaf.02) is that custom AttributeErrors raised in __getattr__ are overridden, which is a pretty severe regression. (Removed, renamed, and reloaded patch.) |
Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.
Show more details
GitHub fields:
bugs.python.org fields:
The text was updated successfully, but these errors were encountered: