builtins.TypeError: catching classes that do not inherit from BaseException is not allowed

Chris Angelico rosuav at gmail.com
Thu Dec 30 10:23:05 EST 2021


On Fri, Dec 31, 2021 at 2:00 AM hongy... at gmail.com
<hongyi.zhao at gmail.com> wrote:
>
> I try to compute the factorial of a large number with tail-recursion optimization decorator in Python3. The following code snippet is converted from the code snippet given here [1] by the following steps:
>
> $ pyenv shell datasci
> $ python --version
> Python 3.9.1
> $ pip install 2to3
> $ 2to3 -w this-script.py
>
> ```
> # This program shows off a python decorator(
> # which implements tail call optimization. It
> # does this by throwing an exception if it is
> # its own grandparent, and catching such
> # exceptions to recall the stack.
>
> import sys
>
> class TailRecurseException:
>   def __init__(self, args, kwargs):
>     self.args = args
>     self.kwargs = kwargs
>

If it's an exception, it needs to subclass Exception or BaseException.

(Also, is this REALLY an optimization? Exception handling isn't the
fastest. Yes, it avoids some measure of recursion depth, but it looks
like a pretty inefficient way to do things. Python is not Lisp, and
there are very very few algorithms that actually benefit from tail
call optimization that wouldn't benefit far more from other ways of
doing the same thing.)

ChrisA


More information about the Python-list mailing list