Steve Jorgensen writes:
> Paul Moore wrote:
> > The built in exceptions are ones that are raised by the core interpreter.
> OK, but by that logic, why do we have standard exceptions like
> `ValueError` when we could define custom exceptions for the cases
> where that should be raised?
I get 154 hits for PyExc_ValueError in cpython/Python. That's exactly
the logic that Paul mentions. :-)
I suspect that the reason that there is no PyExc_InvalidStateError is
that the interpreter rarely can detect it. For example, in the
following very contrived example
def getcontents(file): # argument should be "filename"
# Oops, forgot to open the file named by `file`.
return file.read()
you'll get an AttributeError. If you typecheck `file` at the top of
the function, ValueError is appropriate. It's not hard to contrive a
case where you can detect it:
>>> with open(RandomExistingFile) as f:
... f.close()
... f.read()
...
Traceback (most recent call last):
File "<stdin>", line 3, in <module>
ValueError: I/O operation on closed file.
and Python chooses to shoehorn the round InvalidStateError peg into
the square ValueError hole. This isn't entirely implausible in
Python's implementation of object-oriented programming: the object `f`
is an invalid value for the `self` argument of the read function.
So, assuming you use this "it's in the interpreter" logic in
advocating this new Error, I would say collect examples of other
errors raised where you would prefer InvalidStateError. If they're
consistently ValueError, I would say you have a case. Probably you
need to derive InvalidStateError from ValueError for backward
compatibility.
_______________________________________________
Python-ideas mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at
https://mail.python.org/archives/list/[email protected]/message/MZQQVUWFB5P35EBYPL2TJRUE5OCQ7XB3/
Code of Conduct: http://python.org/psf/codeofconduct/