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

Eric V. Smith eric at trueblade.com
Mon Dec 16 17:21:26 CET 2013


On 12/16/2013 10:29 AM, Walter Dörwald wrote:
> I'd vote for including the module name in the string and using
> __qualname__ instead of __name__, i.e. make "{:T}".format(obj)
> equivalent to
> "{0.__class__.__module__}.{0.__class__.qualname__}".format(obj).

That's not possible in general. The format specifier interpretation is
done by each type. So, you could add this to str.__format__ and
int.__format__, but you can't add it to an arbitrary type's __format__.
For example, types not in the stdlib would never know about it.

There's no logic for calling through to object.__format__ for unknown
specifiers. Look at datetime, for example. It uses strftime, so "T"
currently just prints a literal "T".

And for object.__format__, we recently made it an error to specify any
format string. This is to prevent you from calling
format(an_object, ".30")
and "knowning" that it's interpreted by str.__format__ (because that's
the default conversion for object.__format__). If in the future
an_object's class added its own __format__, this code would break (or at
least do the wrong thing).

But I really do like the idea! Maybe there's a way to just make
obj.__class__ recognize "T", so you could at least do:
format(obj.__class__, "T")
or equivalently:
"{:T}".format(obj.__class__)

I realize that having to use .__class__ defeats some of the beauty of
this scheme.

Eric.




More information about the Python-Dev mailing list