[Python-Dev] __getattr__ and new style classes

Kristján Valur Jónsson kristjan at ccpgames.com
Thu Oct 9 16:09:37 CEST 2008


It's an interesting idea...  But it seems hard to forge the magic that
does this (creating it in args[0] on demand) without some heavy work.

In my opinion, the problem is that we are raising all these errors
at all, with object creation and all that it entails.  We are using
exceptions very much as program logic to test for the existence of
attributes.

Python itself has the getattr(obj, attr, default) thing, encouraging
you to not use exceptions where the absence of an attribute is
fully excpected.  But the C layer doesn't have this.

In my opinion, the C api should have this capability, which is why
I bothered with implementing PyObject_GetAttrSoft() there.
Ideally, it should have a signature such as:
int PyObject_GetAttrSoft(PyObject **result, PyObject *obj, PyObject *attr, int raise);
where the return value indicates success (0) or an exception (-1) and the
"result" gets either NULL or something else in case of success.
"raise" would indicate whether we want the absence of an attibute to raise
an exception or not.

Now this is all well and good, but the big problem is that we invariably
end up calling the tp->tp_getattr slots that have no such functionality.

I'd actually be more inclined to try to go for a full solution using a
tp_gettattrc (c for conditional) with a default implementation....
Maybe I'll play with that over the weekend, see where it takes us.

K

> -----Original Message-----
> From: Nick Coghlan [mailto:ncoghlan at gmail.com]
> Sent: Thursday, October 09, 2008 11:54
> To: Kristján Valur Jónsson
> Cc: Python-Dev
> Subject: Re: [Python-Dev] __getattr__ and new style classes
>
> Kristján Valur Jónsson wrote:
> > Running regular python code through a profiler, and especially code
> that relies much on the use of
> > __getattr__() to emulate attribute access, will show hideous amounts
> of time spent formatting
> > attribute exceptions that get thrown away.
> >
> > Any thoughts on how to do this better?
>
> If the time is being spent in PyErr_Format, how far could you get
> adding
> a dedicated function for creating AttributeErrors? Something along the
> lines of:
>
> PyErr_AttributeError(PyObject *object, PyObject *attr_name)
>
> It would then be possible to modify AttributeError to have obj_type and
> attr_name attributes (holding the type name and the name of the missing
> attribute), so that any string formatting could be deferred until
> repr()
> was called on the AttributeError instance.
>
> Cheers,
> Nick.
>
> --
> Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia
> ---------------------------------------------------------------
>             http://www.boredomandlaziness.org



More information about the Python-Dev mailing list