[Python-Dev] How long the wrong type of argument should we limit (or not) in the error message (C-api)?

Steven D'Aprano steve at pearwood.info
Mon Dec 16 02:23:10 CET 2013

On Mon, Dec 16, 2013 at 07:30:56AM +1000, Nick Coghlan wrote:
> On 16 Dec 2013 02:58, "Ethan Furman" <ethan at stoneleaf.us> wrote:
> >
> > On 12/14/2013 07:51 PM, Steven D'Aprano wrote:
> >>
> >> On Sun, Dec 15, 2013 at 11:25:10AM +1000, Nick Coghlan wrote:
> >>
> >>> Oh, yes, a %T shortcut for "length limited type name of the supplied
> >>> object" would be brilliant. We need this frequently for C level error
> >>> messages, and I almost always have to look at an existing example to
> >>> remember the exact incantation :)
> >>
> >>
> >> What are the chances that could be made available from pure Python too?
> >> Having to extract the name of the type is a very common need for error
> >> messages, and I never know whether I ought to write type(obj).__name__
> >> or obj.__class__.__name__. A %T and/or {:T} format code could be the One
> >> Obvious Way to include the type name in strings
> >
> >
> > +1
> It's less obviously correct for Python code, though. In C, we're almost
> always running off slots, so type(obj).__name__ has a very high chance of
> being what we want, and is also preferred for speed reasons (since it's
> just a couple of pointer dereferences).
> At the Python level, whether to display obj.__name__ (working with a class
> directly), type(obj).__name__ (working with the concrete type, ignoring any
> proxying) or obj.__class__.__name__ (which takes proxying into account)
> really depends on exactly what you're doing, and the speed differences
> between them aren't so stark.

That's a good point, but I think most coders would have a very fuzzy 
idea of the difference between type(obj).__name__ and 
obj.__class__.__name__, and when to use one versus the other. I know I 
don't have a clue, and nearly always end up just arbitrarily picking 
one. It would be a good thing if the 95% of the time that I don't need 
to think about it, I don't need to think about it and just use {:T} 
formatting code. The other 5% of the time I can always extract the name 
manually, as before.

Likewise, I think that most of the time it is useful to distinguish 
between instances and classes, metaclasses not withstanding. If obj 
is itself a class, we should see its name directly, and not the name of 
its class (which will generally be "type"). In other words, what I 
usually want to write is:

    raise TypeError("some error regarding type '%s'" % 
         obj.__name__ if isinstance(obj, type) else type(obj).__name__

(modulo difference between type(obj) and obj.__class__, as above), but 
what I end up doing is take the lazy way out and unconditionally use 

But this is getting further away from the %T formatting code at the C 
level, so perhaps it needs to go to Python Ideas first?


More information about the Python-Dev mailing list