Repository: ipython/ipython

Issue:
IPython crashes when failing to create a numpy array
I was playing around with `numpy` inside an `ipython` shell in a virtual environment for my project (both numpy and ipython are installed in the virtual environment as they should be), and I came across a snippet of code, which clearly raises a `TypeError`. However, rather than displaying the error and keep playing in the shell, ipython crashed with more errors than expected and sent me back to my system shell.

### Output of `IPython.sys_info()`:
{'commit_hash': 'e9b2ec3bc',
 'commit_source': 'installation',
 'default_encoding': 'utf-8',
 'ipython_path': 'D:\\dev\\python\\PhysiScript\\.venv\\Lib\\site-packages\\IPython',
 'ipython_version': '8.1.1',
 'os_name': 'nt',
 'platform': 'Windows-10-10.0.22000-SP0',
 'sys_executable': 'D:\\dev\\python\\PhysiScript\\.venv\\Scripts\\python.exe',
 'sys_platform': 'win32',
 'sys_version': '3.10.2 (tags/v3.10.2:a58ebcc, Jan 17 2022, 14:12:15) [MSC '
                'v.1929 64 bit (AMD64)]'}

### Code which caused the crash:
```
In [1]: import numpy as np

In [2]: class Foo:
   ...:     def __float__(self):
   ...:         return 10.5
   ...:

In [3]: np.fromiter(["1", "2", Foo(), []], dtype=np.float64)
```

### Errors reported:
```
Error in sys.excepthook:
Traceback (most recent call last):
  File "D:\.pyenv\pyenv-win\versions\3.10.2\lib\pathlib.py", line 1303, in is_dir
    return S_ISDIR(self.stat().st_mode)
AttributeError: 'str' object has no attribute 'stat'

Original exception was:
TypeError: float() argument must be a string or a real number, not 'list'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "D:\dev\python\PhysiScript\.venv\lib\site-packages\IPython\core\interactiveshell.py", line 3361, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-5-38c7f7fe40c5>", line 1, in <cell line: 1>
ValueError: setting an array element with a sequence.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "D:\dev\python\PhysiScript\.venv\lib\site-packages\IPython\core\interactiveshell.py", line 1979, in showtraceback
    stb = value._render_traceback_()
AttributeError: 'ValueError' object has no attribute '_render_traceback_'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "D:\dev\python\PhysiScript\.venv\lib\site-packages\IPython\core\interactiveshell.py", line 3301, in run_ast_nodes
    if await self.run_code(code, result, async_=asy):
  File "D:\dev\python\PhysiScript\.venv\lib\site-packages\IPython\core\interactiveshell.py", line 3378, in run_code
    self.showtraceback(running_compiled_code=True)
  File "D:\dev\python\PhysiScript\.venv\lib\site-packages\IPython\core\interactiveshell.py", line 1981, in showtraceback
    stb = self.InteractiveTB.structured_traceback(etype,
  File "D:\dev\python\PhysiScript\.venv\lib\site-packages\IPython\core\ultratb.py", line 1105, in structured_traceback
    return FormattedTB.structured_traceback(
  File "D:\dev\python\PhysiScript\.venv\lib\site-packages\IPython\core\ultratb.py", line 999, in structured_traceback
    return VerboseTB.structured_traceback(
  File "D:\dev\python\PhysiScript\.venv\lib\site-packages\IPython\core\ultratb.py", line 871, in structured_traceback
    formatted_exceptions += self.format_exception_as_a_whole(etype, evalue, etb, lines_of_context,
  File "D:\dev\python\PhysiScript\.venv\lib\site-packages\IPython\core\ultratb.py", line 775, in format_exception_as_a_whole
    assert etb is not None
AssertionError

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "D:\dev\python\PhysiScript\.venv\lib\site-packages\IPython\core\interactiveshell.py", line 1979, in showtraceback
    stb = value._render_traceback_()
AttributeError: 'AssertionError' object has no attribute '_render_traceback_'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "D:\dev\python\PhysiScript\.venv\lib\site-packages\IPython\core\interactiveshell.py", line 2900, in _run_cell
    return runner(coro)
  File "D:\dev\python\PhysiScript\.venv\lib\site-packages\IPython\core\async_helpers.py", line 129, in _pseudo_sync_runner
    coro.send(None)
  File "D:\dev\python\PhysiScript\.venv\lib\site-packages\IPython\core\interactiveshell.py", line 3098, in run_cell_async
    has_raised = await self.run_ast_nodes(code_ast.body, cell_name,
  File "D:\dev\python\PhysiScript\.venv\lib\site-packages\IPython\core\interactiveshell.py", line 3320, in run_ast_nodes
    self.showtraceback()
  File "D:\dev\python\PhysiScript\.venv\lib\site-packages\IPython\core\interactiveshell.py", line 1981, in showtraceback
    stb = self.InteractiveTB.structured_traceback(etype,
  File "D:\dev\python\PhysiScript\.venv\lib\site-packages\IPython\core\ultratb.py", line 1105, in structured_traceback
    return FormattedTB.structured_traceback(
  File "D:\dev\python\PhysiScript\.venv\lib\site-packages\IPython\core\ultratb.py", line 999, in structured_traceback
    return VerboseTB.structured_traceback(
  File "D:\dev\python\PhysiScript\.venv\lib\site-packages\IPython\core\ultratb.py", line 871, in structured_traceback
    formatted_exceptions += self.format_exception_as_a_whole(etype, evalue, etb, lines_of_context,
  File "D:\dev\python\PhysiScript\.venv\lib\site-packages\IPython\core\ultratb.py", line 775, in format_exception_as_a_whole
    assert etb is not None
AssertionError

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "D:\dev\python\PhysiScript\.venv\lib\site-packages\IPython\core\interactiveshell.py", line 1979, in showtraceback
    stb = value._render_traceback_()
AttributeError: 'AssertionError' object has no attribute '_render_traceback_'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "D:\.pyenv\pyenv-win\versions\3.10.2\lib\runpy.py", line 196, in _run_module_as_main
    return _run_code(code, main_globals, None,
  File "D:\.pyenv\pyenv-win\versions\3.10.2\lib\runpy.py", line 86, in _run_code
    exec(code, run_globals)
  File "D:\dev\python\PhysiScript\.venv\Scripts\ipython.exe\__main__.py", line 7, in <module>
  File "D:\dev\python\PhysiScript\.venv\lib\site-packages\IPython\__init__.py", line 123, in start_ipython
    return launch_new_instance(argv=argv, **kwargs)
  File "D:\dev\python\PhysiScript\.venv\lib\site-packages\traitlets\config\application.py", line 846, in launch_instance
    app.start()
  File "D:\dev\python\PhysiScript\.venv\lib\site-packages\IPython\terminal\ipapp.py", line 318, in start
    self.shell.mainloop()
  File "D:\dev\python\PhysiScript\.venv\lib\site-packages\IPython\terminal\interactiveshell.py", line 653, in mainloop
    self.interact()
  File "D:\dev\python\PhysiScript\.venv\lib\site-packages\IPython\terminal\interactiveshell.py", line 646, in interact
    self.run_cell(code, store_history=True)
  File "D:\dev\python\PhysiScript\.venv\lib\site-packages\IPython\core\interactiveshell.py", line 2854, in run_cell
    result = self._run_cell(
  File "D:\dev\python\PhysiScript\.venv\lib\site-packages\IPython\core\interactiveshell.py", line 2905, in _run_cell
    self.showtraceback(running_compiled_code=True)
  File "D:\dev\python\PhysiScript\.venv\lib\site-packages\IPython\core\interactiveshell.py", line 1981, in showtraceback
    stb = self.InteractiveTB.structured_traceback(etype,
  File "D:\dev\python\PhysiScript\.venv\lib\site-packages\IPython\core\ultratb.py", line 1105, in structured_traceback
    return FormattedTB.structured_traceback(
  File "D:\dev\python\PhysiScript\.venv\lib\site-packages\IPython\core\ultratb.py", line 999, in structured_traceback
    return VerboseTB.structured_traceback(
  File "D:\dev\python\PhysiScript\.venv\lib\site-packages\IPython\core\ultratb.py", line 871, in structured_traceback
    formatted_exceptions += self.format_exception_as_a_whole(etype, evalue, etb, lines_of_context,
  File "D:\dev\python\PhysiScript\.venv\lib\site-packages\IPython\core\ultratb.py", line 775, in format_exception_as_a_whole
    assert etb is not None
AssertionError
```

Note: these errors were generated after running `%config Application.verbose_crash=True` to allow more complete output. However, most of these errors are generated without it as well.

The only "real" error here was to initialize a 1D array from an empty sublist (the last argument of the list in `fromiter`). All the others look like `ipython` errors.
ipython3 crash: nested exceptions?
I just recently started getting seemingly random crashes - complete crash of the kernel, requring restart -- that appear to be related to exceptions occurring within the exception handler. The trigger appears completely random, but always starts with some sort of reasonable error at the console, followed by a long stack trace. Something like this, where the "Original exception" is my mistake:
```
Original exception was:
Traceback (most recent call last):
  File "/home/mazer/.local/lib/python3.8/site-packages/IPython/core/interactiveshell.py", line 3361, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-131-ddf36e5e5914>", line 1, in <cell line: 1>
  File "/home/mazer/src/taut/notebooks/jamie/graph-audio/debugger.py", line 238, in run_pipeline
    sup.title(f'sentence # {sampleno}')
NameError: name 'sup' is not defined
....
```
During handling of the above exception caused by my typo, another exception occurrs inside ipython:

```
Traceback (most recent call last):
  File "/home/mazer/.local/lib/python3.8/site-packages/IPython/core/interactiveshell.py", line 1979, in showtraceback
    stb = value._render_traceback_()
AttributeError: 'NameError' object has no attribute '_render_traceback_'
```
followed by along, inconsistent stack trace that always ends with:
```
  File "/home/mazer/.local/lib/python3.8/site-packages/stack_data/core.py", line 628, in executing_piece
    return only(
  File "/home/mazer/.local/lib/python3.8/site-packages/executing/executing.py", line 164, in only
    raise NotOneValueFound('Expected one value, found 0')
executing.executing.NotOneValueFound: Expected one value, found 0
```
Just started getting this since I did a fresh update/install of the virtualenv I'm using.

Anybody seen this or have any ideas about what might be causing this?

Thanks,
Jamie




Discussion:
I got a similar problem here. Running Windows 10 with Python 3.10.2.
I verified that IPython, ipykernel, and jupyterlab are all the most recent available versions.
```
[IPKernelApp] ERROR | Exception in message handler:
joblib.externals.loky.process_executor._RemoteTraceback:
"""
Traceback (most recent call last):
  File "C:\Users\anonymoususer\AppData\Local\Programs\Python\Python310\lib\site-packages\joblib\externals\loky\process_executor.py", line 436, in _process_worker
    r = call_item()
  File "C:\Users\anonymoususer\AppData\Local\Programs\Python\Python310\lib\site-packages\joblib\externals\loky\process_executor.py", line 288, in __call__
    return self.fn(*self.args, **self.kwargs)
  File "C:\Users\anonymoususer\AppData\Local\Programs\Python\Python310\lib\site-packages\joblib\_parallel_backends.py", line 595, in __call__
    return self.func(*args, **kwargs)
  File "C:\Users\anonymoususer\AppData\Local\Programs\Python\Python310\lib\site-packages\joblib\parallel.py", line 262, in __call__
    return [func(*args, **kwargs)
  File "C:\Users\anonymoususer\AppData\Local\Programs\Python\Python310\lib\site-packages\joblib\parallel.py", line 262, in <listcomp>
    return [func(*args, **kwargs)
  File "C:\Users\anonymoususer\AppData\Local\Programs\Python\Python310\lib\site-packages\sklearn\utils\fixes.py", line 216, in __call__
    return self.function(*args, **kwargs)
  File "C:\Users\anonymoususer\AppData\Local\Programs\Python\Python310\lib\site-packages\sklearn\ensemble\_bagging.py", line 141, in _parallel_predict_proba
    proba_estimator = estimator.predict_proba(X[:, features])
  File "C:\Users\anonymoususer\AppData\Local\Programs\Python\Python310\lib\site-packages\sklearn\tree\_classes.py", line 971, in predict_proba
    X = self._validate_X_predict(X, check_input)
  File "C:\Users\anonymoususer\AppData\Local\Programs\Python\Python310\lib\site-packages\sklearn\tree\_classes.py", line 433, in _validate_X_predict
    X = self._validate_data(X, dtype=DTYPE, accept_sparse="csr", reset=False)
  File "C:\Users\anonymoususer\AppData\Local\Programs\Python\Python310\lib\site-packages\sklearn\base.py", line 566, in _validate_data
    X = check_array(X, **check_params)
  File "C:\Users\anonymoususer\AppData\Local\Programs\Python\Python310\lib\site-packages\sklearn\utils\validation.py", line 800, in check_array
    _assert_all_finite(array, allow_nan=force_all_finite == "allow-nan")
  File "C:\Users\anonymoususer\AppData\Local\Programs\Python\Python310\lib\site-packages\sklearn\utils\validation.py", line 114, in _assert_all_finite
    raise ValueError(
ValueError: Input contains NaN, infinity or a value too large for dtype('float32').
"""

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\anonymoususer\AppData\Local\Programs\Python\Python310\lib\site-packages\IPython\core\interactiveshell.py", line 3251, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "C:\Users\anonymoususer\AppData\Local\Temp\ipykernel_3772\590992968.py", line 8, in <module>
    test_pipeline(pipeline, fnr, fpr, min_confidence)
  File "C:\Users\anonymoususer\AppData\Local\Temp\ipykernel_3772\410483082.py", line 19, in test_pipeline
    prediction_probas = pipeline.predict_proba(df_test_with_errors[attack_ids])
  File "C:\Users\anonymoususer\AppData\Local\Programs\Python\Python310\lib\site-packages\sklearn\utils\metaestimators.py", line 113, in <lambda>
    out = lambda *args, **kwargs: self.fn(obj, *args, **kwargs)  # noqa
  File "C:\Users\anonymoususer\AppData\Local\Programs\Python\Python310\lib\site-packages\sklearn\pipeline.py", line 536, in predict_proba
    return self.steps[-1][1].predict_proba(Xt, **predict_proba_params)
  File "C:\Users\anonymoususer\AppData\Local\Programs\Python\Python310\lib\site-packages\sklearn\ensemble\_bagging.py", line 784, in predict_proba
    all_proba = Parallel(
  File "C:\Users\anonymoususer\AppData\Local\Programs\Python\Python310\lib\site-packages\joblib\parallel.py", line 1056, in __call__
    self.retrieve()
  File "C:\Users\anonymoususer\AppData\Local\Programs\Python\Python310\lib\site-packages\joblib\parallel.py", line 935, in retrieve
    self._output.extend(job.get(timeout=self.timeout))
  File "C:\Users\anonymoususer\AppData\Local\Programs\Python\Python310\lib\site-packages\joblib\_parallel_backends.py", line 542, in wrap_future_result
    return future.result(timeout=timeout)
  File "C:\Users\anonymoususer\AppData\Local\Programs\Python\Python310\lib\concurrent\futures\_base.py", line 446, in result
    return self.__get_result()
  File "C:\Users\anonymoususer\AppData\Local\Programs\Python\Python310\lib\concurrent\futures\_base.py", line 391, in __get_result
    raise self._exception
ValueError: Input contains NaN, infinity or a value too large for dtype('float32').

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\anonymoususer\AppData\Local\Programs\Python\Python310\lib\site-packages\IPython\core\interactiveshell.py", line 1934, in showtraceback
    stb = value._render_traceback_()
AttributeError: 'ValueError' object has no attribute '_render_traceback_'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\anonymoususer\AppData\Local\Programs\Python\Python310\lib\site-packages\IPython\core\interactiveshell.py", line 3191, in run_ast_nodes
    if await self.run_code(code, result, async_=asy):
  File "C:\Users\anonymoususer\AppData\Local\Programs\Python\Python310\lib\site-packages\IPython\core\interactiveshell.py", line 3268, in run_code
    self.showtraceback(running_compiled_code=True)
  File "C:\Users\anonymoususer\AppData\Local\Programs\Python\Python310\lib\site-packages\IPython\core\interactiveshell.py", line 1936, in showtraceback
    stb = self.InteractiveTB.structured_traceback(etype,
  File "C:\Users\anonymoususer\AppData\Local\Programs\Python\Python310\lib\site-packages\IPython\core\ultratb.py", line 1105, in structured_traceback
    return FormattedTB.structured_traceback(
  File "C:\Users\anonymoususer\AppData\Local\Programs\Python\Python310\lib\site-packages\IPython\core\ultratb.py", line 999, in structured_traceback
    return VerboseTB.structured_traceback(
  File "C:\Users\anonymoususer\AppData\Local\Programs\Python\Python310\lib\site-packages\IPython\core\ultratb.py", line 871, in structured_traceback
    formatted_exceptions += self.format_exception_as_a_whole(etype, evalue, etb, lines_of_context,
  File "C:\Users\anonymoususer\AppData\Local\Programs\Python\Python310\lib\site-packages\IPython\core\ultratb.py", line 775, in format_exception_as_a_whole
    assert etb is not None
AssertionError

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\anonymoususer\AppData\Local\Programs\Python\Python310\lib\site-packages\IPython\core\interactiveshell.py", line 1934, in showtraceback
    stb = value._render_traceback_()
AttributeError: 'AssertionError' object has no attribute '_render_traceback_'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\anonymoususer\AppData\Local\Programs\Python\Python310\lib\site-packages\IPython\core\interactiveshell.py", line 2814, in _run_cell
    return runner(coro)
  File "C:\Users\anonymoususer\AppData\Local\Programs\Python\Python310\lib\site-packages\IPython\core\async_helpers.py", line 129, in _pseudo_sync_runner
    coro.send(None)
  File "C:\Users\anonymoususer\AppData\Local\Programs\Python\Python310\lib\site-packages\IPython\core\interactiveshell.py", line 3012, in run_cell_async
    has_raised = await self.run_ast_nodes(code_ast.body, cell_name,
  File "C:\Users\anonymoususer\AppData\Local\Programs\Python\Python310\lib\site-packages\IPython\core\interactiveshell.py", line 3210, in run_ast_nodes
    self.showtraceback()
  File "C:\Users\anonymoususer\AppData\Local\Programs\Python\Python310\lib\site-packages\IPython\core\interactiveshell.py", line 1936, in showtraceback
    stb = self.InteractiveTB.structured_traceback(etype,
  File "C:\Users\anonymoususer\AppData\Local\Programs\Python\Python310\lib\site-packages\IPython\core\ultratb.py", line 1105, in structured_traceback
    return FormattedTB.structured_traceback(
  File "C:\Users\anonymoususer\AppData\Local\Programs\Python\Python310\lib\site-packages\IPython\core\ultratb.py", line 999, in structured_traceback
    return VerboseTB.structured_traceback(
  File "C:\Users\anonymoususer\AppData\Local\Programs\Python\Python310\lib\site-packages\IPython\core\ultratb.py", line 871, in structured_traceback
    formatted_exceptions += self.format_exception_as_a_whole(etype, evalue, etb, lines_of_context,
  File "C:\Users\anonymoususer\AppData\Local\Programs\Python\Python310\lib\site-packages\IPython\core\ultratb.py", line 775, in format_exception_as_a_whole
    assert etb is not None
AssertionError

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\anonymoususer\AppData\Local\Programs\Python\Python310\lib\site-packages\IPython\core\interactiveshell.py", line 1934, in showtraceback
    stb = value._render_traceback_()
AttributeError: 'AssertionError' object has no attribute '_render_traceback_'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\anonymoususer\AppData\Local\Programs\Python\Python310\lib\site-packages\ipykernel\kernelbase.py", line 367, in dispatch_shell
    await result
  File "C:\Users\anonymoususer\AppData\Local\Programs\Python\Python310\lib\site-packages\ipykernel\kernelbase.py", line 662, in execute_request
    reply_content = await reply_content
  File "C:\Users\anonymoususer\AppData\Local\Programs\Python\Python310\lib\site-packages\ipykernel\ipkernel.py", line 360, in do_execute
    res = shell.run_cell(code, store_history=store_history, silent=silent)
  File "C:\Users\anonymoususer\AppData\Local\Programs\Python\Python310\lib\site-packages\ipykernel\zmqshell.py", line 532, in run_cell
    return super().run_cell(*args, **kwargs)
  File "C:\Users\anonymoususer\AppData\Local\Programs\Python\Python310\lib\site-packages\IPython\core\interactiveshell.py", line 2768, in run_cell
    result = self._run_cell(
  File "C:\Users\anonymoususer\AppData\Local\Programs\Python\Python310\lib\site-packages\IPython\core\interactiveshell.py", line 2819, in _run_cell
    self.showtraceback(running_compiled_code=True)
  File "C:\Users\anonymoususer\AppData\Local\Programs\Python\Python310\lib\site-packages\IPython\core\interactiveshell.py", line 1936, in showtraceback
    stb = self.InteractiveTB.structured_traceback(etype,
  File "C:\Users\anonymoususer\AppData\Local\Programs\Python\Python310\lib\site-packages\IPython\core\ultratb.py", line 1105, in structured_traceback
    return FormattedTB.structured_traceback(
  File "C:\Users\anonymoususer\AppData\Local\Programs\Python\Python310\lib\site-packages\IPython\core\ultratb.py", line 999, in structured_traceback
    return VerboseTB.structured_traceback(
  File "C:\Users\anonymoususer\AppData\Local\Programs\Python\Python310\lib\site-packages\IPython\core\ultratb.py", line 871, in structured_traceback
    formatted_exceptions += self.format_exception_as_a_whole(etype, evalue, etb, lines_of_context,
  File "C:\Users\anonymoususer\AppData\Local\Programs\Python\Python310\lib\site-packages\IPython\core\ultratb.py", line 775, in format_exception_as_a_whole
    assert etb is not None
AssertionError
```


Resolving patch:
diff --git a/IPython/core/ultratb.py b/IPython/core/ultratb.py
--- a/IPython/core/ultratb.py
+++ b/IPython/core/ultratb.py
@@ -763,7 +763,7 @@ def format_exception_as_a_whole(
         self,
         etype: type,
         evalue: BaseException,
-        etb: TracebackType,
+        etb: Optional[TracebackType],
         number_of_lines_of_context,
         tb_offset: Optional[int],
     ):
@@ -772,7 +772,6 @@ def format_exception_as_a_whole(
         This may be called multiple times by Python 3 exception chaining
         (PEP 3134).
         """
-        assert etb is not None
         # some locals
         orig_etype = etype
         try:
@@ -783,7 +782,9 @@ def format_exception_as_a_whole(
         tb_offset = self.tb_offset if tb_offset is None else tb_offset
         assert isinstance(tb_offset, int)
         head = self.prepare_header(etype, self.long_header)
-        records = self.get_records(etb, number_of_lines_of_context, tb_offset)
+        records = (
+            self.get_records(etb, number_of_lines_of_context, tb_offset) if etb else []
+        )
 
         frames = []
         skipped = 0
@@ -822,6 +823,7 @@ def format_exception_as_a_whole(
     def get_records(
         self, etb: TracebackType, number_of_lines_of_context: int, tb_offset: int
     ):
+        assert etb is not None
         context = number_of_lines_of_context - 1
         after = context // 2
         before = context - after
@@ -836,19 +838,17 @@ def get_records(
             after=after,
             pygments_formatter=formatter,
         )
-        assert etb is not None
         return list(stack_data.FrameInfo.stack_data(etb, options=options))[tb_offset:]
 
     def structured_traceback(
         self,
         etype: type,
         evalue: Optional[BaseException],
-        etb: TracebackType,
+        etb: Optional[TracebackType],
         tb_offset: Optional[int] = None,
         number_of_lines_of_context: int = 5,
     ):
         """Return a nice text document describing the traceback."""
-        assert etb is not None
         formatted_exception = self.format_exception_as_a_whole(etype, evalue, etb, number_of_lines_of_context,
                                                                tb_offset)
 


Test patch: