Str.format for type

I’ve also found myself printing {type(a).__name__}: {a=} recently.

It will be helpful if there is an easier way to do it in the future.

Given that this is implemented in C API, I think there is a high chance that this will eventually end up in Python as well.

But as it has been rejected recently, I think some time needs to pass before attempting to suggest it again.

I wasn’t going to push for it. But seeing as the PEP discussion ended with

Thank you very much to everybody who was involved in the scattered discussion about PEP 737, and thanks to the Steering Council for reviewing and accepting my PEP!

It’s now implemented in the main branch. Let’s see how it goes :wink:

I’m hopeful it will end up in my working python version eventually

In the mean time, do you know a better way to do

with Exception as e:
    logger.warn(f"Error parsing {file}: {e.__class__.__name__}({e})")

to properly print ErrorName(error message)?

1 Like

More thorough use case search:

CPython

  • type(...).__name__ - 155
  • .__class__.__name__ - 264

Github

  • type(...).__name__ - 602K
  • .__class__.__name__ - 844K

Might want to add __qualname__ as well in your search?

Not many __qualname__ hits, but could be useful nevertheless:

CPython

  • type(...).__qualname__ - 0 matches
  • .__class__.__qualname__ - 0 matches

Github

  • type(...).__qualname__ - 6K files
  • .__class__.__qualname__ - 8.4K files

Note that there might be occurrences of:

cls = self.__class__
return f"{cls.__module__}.{cls.__name__} ..."

Also, I found 24 matches of .__class__.__qualname__ in CPython, e.g., in _pydatetime or _pyio and quite a lot of .__qualname__ on type objects in typing.

1 Like

Well as I’ve mentioned I just go:

 logger.warn(f"Error parsing {file!r}: {s(e)}")

or r(e) or often just e as seems appropriate.

But equally, for some things I’ll have gone something like:

 try:
     pfx_call(parse, file)
 except SyntaxError as e:
     warning("parse fails: %s", e)

because pfx_call will have patched the exception message for me with
the function name and the arguments I called it with. And any outer
Pfx context managers in play when this was called. Makes for simpler
warning() calls where less context needs to be provided at the call
because the context managers supply the salient ones. I’ve a whole
cs.pfx package just for this convenience.

Thanks for this. It did seem a bit too low:

CPython

  • type(...).__qualname__ - 8 matches
  • .__class__.__qualname__ - 24 matches