[Python-ideas] exception instantiation philosophy and practice [was: Let try-except check the exception instance]

Eric Fahlgren ericfahlgren at gmail.com
Fri Jun 1 09:47:45 EDT 2018


On Thu, May 31, 2018 at 10:55 PM Greg Ewing <greg.ewing at canterbury.ac.nz>
wrote:

> Ethan Furman wrote:
>
> > Why is this?  Doesn't the exception have to be instantiated at some
> > point, even if just to print to stderr?
>
> If it gets caught by an except clause without an else clause,
> in theory there's no need to instantiate it.
>
> However, Python doesn't currently seem to take advantage of
> that:
>
>  >>>
> ​​
> class E(Exception):
> ...  def __init__(self, *args):
> ...   Exception.__init__(self, *args)
> ...   print("E got instantiated!")
> ...
>  >>> try:
> ...  print("Trying")
> ...  raise E
> ... except E:
> ...  print("Caught an E")
> ...
> Trying
> E got instantiated!
> Caught an E


​I don't think it's possible to avoid instantiating the exception at the
user level, what would sys.exc_info() do about it's second return value?

I believe the only cases where it's possible to avoid instantiation are
inside the interpreter itself, where the exception never propagates up to
user visibility.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20180601/9bfa4005/attachment.html>


More information about the Python-ideas mailing list