You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
E TypeError Traceback (most recent call last)
E /var/folders/jk/bq46f4ys107bjb6jwvn0yhqr0000gp/T/ipykernel_52132/3127954361.py in
E ----> 1 some_function(*(0, "[1]", "[0]", "[1]", "<ufunc 'sign'>", ), **{})
E
E /var/folders/jk/bq46f4ys107bjb6jwvn0yhqr0000gp/T/ipykernel_52132/179938020.py in some_function(input_var, first, bias, second, the_transfer_function)
E 1 def some_function(input_var: float, first: np.ndarray, bias: np.ndarray, second: np.ndarray, the_transfer_function):
E ----> 2 h: np.ndarray = input_var * first - bias
E 3 return np.dot(second, the_transfer_function(h))
E
E TypeError: unsupported operand type(s) for -: 'str' and 'str'
E TypeError: unsupported operand type(s) for -: 'str' and 'str'
I have added extra type information to make it clear to you the intend of the code.
Tests inside the notebook are running successfully
def execute_cell(self, cell, **kwargs) -> Union[Dict, List[Dict]]:
"""
Executes a cell or list of cells
"""
if isinstance(cell, slice):
start, stop = self._cell_index(cell.start), self._cell_index(cell.stop)
if cell.step is not None:
raise TestbookError('testbook does not support step argument')
cell = range(start, stop + 1)
elif isinstance(cell, str) or isinstance(cell, int):
cell = [cell]
cell_indexes = cell
if all(isinstance(x, str) for x in cell):
cell_indexes = [self._cell_index(tag) for tag in cell]
executed_cells = []
for idx in cell_indexes:
try:
coro = <coroutine object NotebookClient.async_execute_cell at 0x7f9ef81fea40>
def just_run(coro: Awaitable) -> Any:
"""Make the coroutine run, even if there is an event loop running (using nest_asyncio)"""
# original from vaex/asyncio.py
loop = asyncio._get_running_loop()
if loop is None:
had_running_loop = False
try:
loop = asyncio.get_event_loop()
except RuntimeError:
# we can still get 'There is no current event loop in ...'
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
else:
had_running_loop = True
if had_running_loop:
# if there is a running loop, we patch using nest_asyncio
# to have reentrant event loops
check_ipython()
import nest_asyncio
nest_asyncio.apply()
check_patch_tornado()
self = <_UnixSelectorEventLoop running=False closed=False debug=False>
future = <Task finished name='Task-48' coro=<NotebookClient.async_execute_cell() done, defined at /Users/1000ber-5078/PycharmPr...rted operand type(s) for -: 'str' and 'str'\nTypeError: unsupported operand type(s) for -: 'str' and 'str'\n')>
def run_until_complete(self, future):
"""Run until the Future is done.
If the argument is a coroutine, it is wrapped in a Task.
WARNING: It would be disastrous to call run_until_complete()
with the same coroutine twice -- it would wrap it in two
different Tasks and that can't be good.
Return the Future's result, or raise its exception.
"""
self._check_closed()
self._check_running()
new_task = not futures.isfuture(future)
future = tasks.ensure_future(future, loop=self)
if new_task:
# An exception is raised if the future didn't complete, so there
# is no need to log the "destroy pending task" message
future._log_destroy_pending = False
future.add_done_callback(_run_until_complete_cb)
try:
self.run_forever()
except:
if new_task and future.done() and not future.cancelled():
# The coroutine raised a BaseException. Consume the exception
# to not log a warning, the caller doesn't have access to the
# local task.
future.exception()
raise
finally:
future.remove_done_callback(_run_until_complete_cb)
if not future.done():
raise RuntimeError('Event loop stopped before Future completed.')
async def async_execute_cell(
self,
cell: NotebookNode,
cell_index: int,
execution_count: t.Optional[int] = None,
store_history: bool = True) -> NotebookNode:
"""
Executes a single code cell.
To execute all cells see :meth:`execute`.
Parameters
----------
cell : nbformat.NotebookNode
The cell which is currently being processed.
cell_index : int
The position of the cell within the notebook object.
execution_count : int
The execution count to be assigned to the cell (default: Use kernel response)
store_history : bool
Determines if history should be stored in the kernel (default: False).
Specific to ipython kernels, which can store command histories.
Returns
-------
output : dict
The execution output payload (or None for no output).
Raises
------
CellExecutionError
If execution failed and should raise an exception, this will be raised
with defaults about the failure.
Returns
-------
cell : NotebookNode
The cell which was just processed.
"""
assert self.kc is not None
if cell.cell_type != 'code' or not cell.source.strip():
self.log.debug("Skipping non-executing cell %s", cell_index)
return cell
if self.record_timing and 'execution' not in cell['metadata']:
cell['metadata']['execution'] = {}
self.log.debug("Executing cell:\n%s", cell.source)
cell_allows_errors = (not self.force_raise_errors) and (
self.allow_errors
or "raises-exception" in cell.metadata.get("tags", []))
parent_msg_id = await ensure_async(
self.kc.execute(
cell.source,
store_history=store_history,
stop_on_error=not cell_allows_errors
)
)
# We launched a code cell to execute
self.code_cells_executed += 1
exec_timeout = self._get_timeout(cell)
cell.outputs = []
self.clear_before_next_output = False
task_poll_kernel_alive = asyncio.ensure_future(
self._async_poll_kernel_alive()
)
task_poll_output_msg = asyncio.ensure_future(
self._async_poll_output_msg(parent_msg_id, cell, cell_index)
)
self.task_poll_for_reply = asyncio.ensure_future(
self._async_poll_for_reply(
parent_msg_id, cell, exec_timeout, task_poll_output_msg, task_poll_kernel_alive
)
)
try:
exec_reply = await self.task_poll_for_reply
except asyncio.CancelledError:
# can only be cancelled by task_poll_kernel_alive when the kernel is dead
task_poll_output_msg.cancel()
raise DeadKernelError("Kernel died")
except Exception as e:
# Best effort to cancel request if it hasn't been resolved
try:
# Check if the task_poll_output is doing the raising for us
if not isinstance(e, CellControlSignal):
task_poll_output_msg.cancel()
finally:
raise
if execution_count:
cell['execution_count'] = execution_count
def _check_raise_for_error(
self,
cell: NotebookNode,
exec_reply: t.Optional[t.Dict]) -> None:
if exec_reply is None:
return None
exec_reply_content = exec_reply['content']
if exec_reply_content['status'] != 'error':
return None
cell_allows_errors = (not self.force_raise_errors) and (
self.allow_errors
or exec_reply_content.get('ename') in self.allow_error_names
or "raises-exception" in cell.metadata.get("tags", []))
if not cell_allows_errors:
E nbclient.exceptions.CellExecutionError: An error occurred while executing the following cell:
E ------------------
E
E some_function((0, "[1]", "[0]", "[1]", "<ufunc 'sign'>", ), **{})
E
E ------------------
E
E ---------------------------------------------------------------------------
E TypeError Traceback (most recent call last)
E /var/folders/jk/bq46f4ys107bjb6jwvn0yhqr0000gp/T/ipykernel_52132/3127954361.py in
E ----> 1 some_function((0, "[1]", "[0]", "[1]", "<ufunc 'sign'>", ), **{})
E
E /var/folders/jk/bq46f4ys107bjb6jwvn0yhqr0000gp/T/ipykernel_52132/179938020.py in some_function(input_var, first, bias, second, the_transfer_function)
E 1 def some_function(input_var: float, first: np.ndarray, bias: np.ndarray, second: np.ndarray, the_transfer_function):
E ----> 2 h: np.ndarray = input_var * first - bias
E 3 return np.dot(second, the_transfer_function(h))
E
E TypeError: unsupported operand type(s) for -: 'str' and 'str'
E TypeError: unsupported operand type(s) for -: 'str' and 'str'
../venv/lib/python3.8/site-packages/testbook/reference.py:85: in call
return self.tb.value(code)
../venv/lib/python3.8/site-packages/testbook/client.py:273: in value
result = self.inject(code, pop=True)
../venv/lib/python3.8/site-packages/testbook/client.py:237: in inject
cell = TestbookNode(self.execute_cell(inject_idx)) if run else TestbookNode(code_cell)
def execute_cell(self, cell, **kwargs) -> Union[Dict, List[Dict]]:
"""
Executes a cell or list of cells
"""
if isinstance(cell, slice):
start, stop = self._cell_index(cell.start), self._cell_index(cell.stop)
if cell.step is not None:
raise TestbookError('testbook does not support step argument')
cell = range(start, stop + 1)
elif isinstance(cell, str) or isinstance(cell, int):
cell = [cell]
cell_indexes = cell
if all(isinstance(x, str) for x in cell):
cell_indexes = [self._cell_index(tag) for tag in cell]
executed_cells = []
for idx in cell_indexes:
try:
cell = super().execute_cell(self.nb['cells'][idx], idx, **kwargs)
except CellExecutionError as ce:
E testbook.exceptions.TestbookRuntimeError: An error occurred while executing the following cell:
E ------------------
E
E some_function((0, "[1]", "[0]", "[1]", "<ufunc 'sign'>", ), **{})
E
E ------------------
E
E ---------------------------------------------------------------------------
E TypeError Traceback (most recent call last)
E /var/folders/jk/bq46f4ys107bjb6jwvn0yhqr0000gp/T/ipykernel_52132/3127954361.py in
E ----> 1 some_function((0, "[1]", "[0]", "[1]", "<ufunc 'sign'>", ), **{})
E
E /var/folders/jk/bq46f4ys107bjb6jwvn0yhqr0000gp/T/ipykernel_52132/179938020.py in some_function(input_var, first, bias, second, the_transfer_function)
E 1 def some_function(input_var: float, first: np.ndarray, bias: np.ndarray, second: np.ndarray, the_transfer_function):
E ----> 2 h: np.ndarray = input_var * first - bias
E 3 return np.dot(second, the_transfer_function(h))
E
E TypeError: unsupported operand type(s) for -: 'str' and 'str'
E TypeError: unsupported operand type(s) for -: 'str' and 'str'
Hey @midumitrescu! It looks like you're trying to pass in a bunch of non-JSON serializable types into the testbook reference function call - types like non-native numpy array implementations, and a function type.
If you'd like to call your function with such types, we have a way of injecting all your code into the notebook, by using tb.inject
Hello,
i have following test:
having in the notebook:
and I get the following TypeError error:
I have added extra type information to make it clear to you the intend of the code.
Tests inside the notebook are running successfully
test_h2.py:12 (test_some_small_function)
self = <testbook.client.TestbookNotebookClient object at 0x7f9ef824d2e0>
cell = [8], kwargs = {}, cell_indexes = [8], executed_cells = [], idx = 8
../venv/lib/python3.8/site-packages/testbook/client.py:133:
args = (<testbook.client.TestbookNotebookClient object at 0x7f9ef824d2e0>, {'id': '6ac327d5', 'cell_type': 'code', 'metadata'...0m\x1b[0;34m\x1b[0m\x1b[0m\n', "\x1b[0;31mTypeError\x1b[0m: unsupported operand type(s) for -: 'str' and 'str'"]}]}, 8)
kwargs = {}
../venv/lib/python3.8/site-packages/nbclient/util.py:78:
coro = <coroutine object NotebookClient.async_execute_cell at 0x7f9ef81fea40>
../venv/lib/python3.8/site-packages/nbclient/util.py:57:
self = <_UnixSelectorEventLoop running=False closed=False debug=False>
future = <Task finished name='Task-48' coro=<NotebookClient.async_execute_cell() done, defined at /Users/1000ber-5078/PycharmPr...rted operand type(s) for -: 'str' and 'str'\nTypeError: unsupported operand type(s) for -: 'str' and 'str'\n')>
/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/asyncio/base_events.py:616:
self = <testbook.client.TestbookNotebookClient object at 0x7f9ef824d2e0>
cell = {'id': '6ac327d5', 'cell_type': 'code', 'metadata': {'execution': {'iopub.status.busy': '2021-10-23T15:57:12.875064Z',...x1b[0m\x1b[0;34m\x1b[0m\x1b[0m\n', "\x1b[0;31mTypeError\x1b[0m: unsupported operand type(s) for -: 'str' and 'str'"]}]}
cell_index = 8, execution_count = None, store_history = True
../venv/lib/python3.8/site-packages/nbclient/client.py:862:
self = <testbook.client.TestbookNotebookClient object at 0x7f9ef824d2e0>
cell = {'id': '6ac327d5', 'cell_type': 'code', 'metadata': {'execution': {'iopub.status.busy': '2021-10-23T15:57:12.875064Z',...x1b[0m\x1b[0;34m\x1b[0m\x1b[0m\n', "\x1b[0;31mTypeError\x1b[0m: unsupported operand type(s) for -: 'str' and 'str'"]}]}
exec_reply = {'buffers': [], 'content': {'ename': 'TypeError', 'engine_info': {'engine_id': -1, 'engine_uuid': '7b8e70ee-5b55-4029-...e, 'engine': '7b8e70ee-5b55-4029-888b-a23a76f683ca', 'started': '2021-10-23T15:57:12.869603Z', 'status': 'error'}, ...}
E nbclient.exceptions.CellExecutionError: An error occurred while executing the following cell:
E ------------------
E
E some_function((0, "[1]", "[0]", "[1]", "<ufunc 'sign'>", ), **{})
E
E ------------------
E
E ---------------------------------------------------------------------------
E TypeError Traceback (most recent call last)
E /var/folders/jk/bq46f4ys107bjb6jwvn0yhqr0000gp/T/ipykernel_52132/3127954361.py in
E ----> 1 some_function((0, "[1]", "[0]", "[1]", "<ufunc 'sign'>", ), **{})
E
E /var/folders/jk/bq46f4ys107bjb6jwvn0yhqr0000gp/T/ipykernel_52132/179938020.py in some_function(input_var, first, bias, second, the_transfer_function)
E 1 def some_function(input_var: float, first: np.ndarray, bias: np.ndarray, second: np.ndarray, the_transfer_function):
E ----> 2 h: np.ndarray = input_var * first - bias
E 3 return np.dot(second, the_transfer_function(h))
E
E TypeError: unsupported operand type(s) for -: 'str' and 'str'
E TypeError: unsupported operand type(s) for -: 'str' and 'str'
../venv/lib/python3.8/site-packages/nbclient/client.py:765: CellExecutionError
During handling of the above exception, another exception occurred:
tb = <testbook.client.TestbookNotebookClient object at 0x7f9ef824d2e0>
test_h2.py:19:
../venv/lib/python3.8/site-packages/testbook/reference.py:85: in call
return self.tb.value(code)
../venv/lib/python3.8/site-packages/testbook/client.py:273: in value
result = self.inject(code, pop=True)
../venv/lib/python3.8/site-packages/testbook/client.py:237: in inject
cell = TestbookNode(self.execute_cell(inject_idx)) if run else TestbookNode(code_cell)
self = <testbook.client.TestbookNotebookClient object at 0x7f9ef824d2e0>
cell = [8], kwargs = {}, cell_indexes = [8], executed_cells = [], idx = 8
E testbook.exceptions.TestbookRuntimeError: An error occurred while executing the following cell:
E ------------------
E
E some_function((0, "[1]", "[0]", "[1]", "<ufunc 'sign'>", ), **{})
E
E ------------------
E
E ---------------------------------------------------------------------------
E TypeError Traceback (most recent call last)
E /var/folders/jk/bq46f4ys107bjb6jwvn0yhqr0000gp/T/ipykernel_52132/3127954361.py in
E ----> 1 some_function((0, "[1]", "[0]", "[1]", "<ufunc 'sign'>", ), **{})
E
E /var/folders/jk/bq46f4ys107bjb6jwvn0yhqr0000gp/T/ipykernel_52132/179938020.py in some_function(input_var, first, bias, second, the_transfer_function)
E 1 def some_function(input_var: float, first: np.ndarray, bias: np.ndarray, second: np.ndarray, the_transfer_function):
E ----> 2 h: np.ndarray = input_var * first - bias
E 3 return np.dot(second, the_transfer_function(h))
E
E TypeError: unsupported operand type(s) for -: 'str' and 'str'
E TypeError: unsupported operand type(s) for -: 'str' and 'str'
../venv/lib/python3.8/site-packages/testbook/client.py:135: TestbookRuntimeError
======================== 1 failed, 12 warnings in 2.97s ========================
Process finished with exit code 1
The text was updated successfully, but these errors were encountered: