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
getattr function w/ default #34437
Comments
In Python 2.1, when calling the builtin getattr Example (providing a non-string as the attribute name): >>> class Test:
... pass
...
>>> t = Test()
>>> getattr(t, 1, "hello")
'hello'
>>> |
Logged In: YES Looks like an attribute error to me. consider this: >>> getattr (t,fred,"thingy")
Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: There is no variable named 'fred' Ie, in your own example, it couldn't find an attribute '1' |
Logged In: YES But consider this: >>> getattr({},1)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: attribute name must be string
>>> getattr({},1,"e")
'e' or >>> getattr(None,u"\343","e")
'e'
>>> getattr(None,u"\343")
Traceback (most recent call last):
File "<stdin>", line 1, in ?
UnicodeError: ASCII encoding error: ordinal not in range(128) Here's a possible patch: Index: bltinmodule.c *** 845,850 **** + /* Internal API needed by builtin_getattr(): */ static PyObject * *** 854,859 ****
if (!PyArg_ParseTuple(args, "OO|O:getattr", &v,
&name, &dflt))
return NULL;
+ if (PyUnicode_Check(name)) {
+ name =
_PyUnicode_AsDefaultEncodedString(name, NULL);
+ if (name == NULL)
+ return NULL;
+ }
+ else if (!PyString_Check(name)) {
+ PyErr_Format(PyExc_TypeError,
+ "getattr: attribute name must be string, not
\"%.500s\"",
+ name->ob_type->tp_name);
+ return NULL;
+ }
result = PyObject_GetAttr(v, name);
if (result == NULL && dflt != NULL) {
PyErr_Clear(); ... though by the time you've done all that, there's not OTOH, this changes behaviour, so maybe one should just |
Logged In: YES This looks like a bug to me, too. I think a non-string attr |
Logged In: YES But unicode attr arguments should be allowed, because |
Logged In: YES Well, the patch I posted below allows unicode (though Have you read the code to object.c:PyObject_GetAttr? All my |
Logged In: YES I guess the right thing to do here, would be to only mask |
Logged In: YES Oh no: getattr hooks can raise any exception whatsoever, The specific complaint here is a different story: the docs Jeremy, I see this is assigned to you now. There are |
Logged In: YES Don't think there's any actual dissent here. You, Michael, Fixed in rev 2.220 of bltinmodule.c |
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: