[Python-Dev] getattribute should require a string? (original) (raw)

Ka-Ping Yee ping@lfw.org
Tue, 4 Dec 2001 04:54:25 -0800 (PST)


In the current Python, getattribute can be called directly with a non-string, causing much weirdness:

>>> print ''.__getattribute__(1)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AttributeError: 'str' object has no attribute ' =E4=B7*'
>>>=20

To avoid this, i've added a simple check to Objects/object.c:

diff -c -r2.161 object.c
*** object.c    2001/11/04 07:29:31     2.161
--- object.c    2001/12/04 12:46:13
***************
*** 1210,1215 ****
--- 1210,1221 ----
        descrgetfunc f;
        PyObject **dictptr;
 =20
+       if (!PyString_Check(name)) {
+               PyErr_SetString(PyExc_TypeError,
+                               "attribute name must be string");
+               return NULL;
+       }
+=20
        if (tp->tp_dict =3D=3D NULL) {
                if (PyType_Ready(tp) < 0)
                        return NULL;

This produces the better behaviour:

>>> print ''.__getattribute__(1)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: attribute name must be string
>>>=20

I was about to check in this simple fix -- but then i discovered that it is currently possible to assign attributes with non-string keys:

>>> def f(): pass
...=20
>>> f.__getattribute__(1)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AttributeError: 'function' object has no attribute ' =E4=B7*'
>>> f.__setattr__(1, 1)
>>> f.__getattribute__(1)
1
>>>=20

Adding the above check prevents this usage.

Is there any reason why people should be allowed to assign and retrieve attributes with non-string names?

-- ?!ng