[Python-ideas] Wild idea: Exception.format

Georg Brandl g.brandl at gmx.net
Fri Sep 18 16:07:35 CEST 2009


To make Exceptions where some object(s) are involved more useful, it is
often necessary to put the objects on the exception *in addition to*
formatting them into a string representation for the message.

This little classmethod would make that easier::

  class BaseException:
    @classmethod
    def format(cls, fmt, *args):
      return cls(fmt.format(*args), *args)

Example usage::

  ext = 'foo'
  raise LookupError.format('Extension {0} not registered', ext)

'foo' could then be accessed as ``exc.args[1]``.


A similar, but also very useful implementation would be ::

  def format(cls, fmt, **kwds):
    exc = cls(fmt.format(**kwds))
    exc.__dict__.update(kwds)
    return exc

with example usage being::

  raise LookupError.format('Extension {ext} not registered', ext='foo')

and 'foo' being accessible as ``exc.ext``.

I realize this is probably too obscure for Python core, but I wanted to
show it to you anyway, maybe it'll be found useful.

Georg

-- 
Thus spake the Lord: Thou shalt indent with four spaces. No more, no less.
Four shall be the number of spaces thou shalt indent, and the number of thy
indenting shall be four. Eight shalt thou not indent, nor either indent thou
two, excepting that thou then proceed to four. Tabs are right out.




More information about the Python-ideas mailing list