Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WIP Recreate old behaviour of ExecutePreprocessor(kernel_name="") #886

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 27 additions & 1 deletion nbconvert/preprocessors/execute.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.

import warnings

from textwrap import dedent
from contextlib import contextmanager

Expand Down Expand Up @@ -161,7 +163,7 @@ class ExecutePreprocessor(Preprocessor):
@default('kernel_name')
def _kernel_name_default(self):
try:
return self.nb.metadata.get('kernelspec', {}).get('name', 'python')
return find_kernel_name(self.nb)
except AttributeError:
raise AttributeError('You did not specify a kernel_name for '
'the ExecutePreprocessor and you have not set '
Expand Down Expand Up @@ -248,6 +250,16 @@ def start_new_kernel(self, **kwargs):
kc : KernelClient
Kernel client as created by the kernel manager `km`.
"""

# Because of an old API, an empty kernel string should be interpreted as indicating
# that you want to use the notebook's metadata specified kernel.
# We use find_kernel_name to do this.
if self.kernel_name == u"":
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would it be better to do if not self.kernel_name:? As a python developer I would expect that if "" is treated as falsy for a condition that None would be too. Or does the kernel_manager_class already handle None separately?

if not self.kernel_name:
  self.kernel_name = find_kernel_name(self.nb)
  if isinstance(self.kernel_name, string_types):
    warnings.warn(...)

Copy link
Member Author

@mpacer mpacer Sep 12, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

After looking at it, I'm pretty sure None would wouldn't have worked previously… but I still don't want to encourage passing people to do this regardless. So we'll want to warn no matter what type the value was.

The reason is that it's specified as a Unicode traitlet so passing in None would cause a validation error.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So would checking for false kernel_name and declaring it deprecated in all cases make more sense from a function perspective then? I'm ok with merging if you feel strongly to just check for unicode string, it just had some code smell for something that might fail under similar situations -- like python version differences

Copy link
Member Author

@mpacer mpacer Sep 12, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The python version difference was why I made it specifically a unicode string (since it's a Unicode() traitlet). I pushed a more general check and added a test to make sure that None raises a TraitError.

self.kernel_name = find_kernel_name(self.nb)
warnings.warn("Setting kernel_name to '' as a way to use the kernel in a notebook metadata's is deprecated as of 5.4. \n"
"Instead, do not set kernel_name, this is now default behaviour.", DeprecationWarning, stacklevel=2)


km = self.kernel_manager_class(kernel_name=self.kernel_name,
config=self.config)
km.start_kernel(extra_arguments=self.extra_arguments, **kwargs)
Expand Down Expand Up @@ -516,6 +528,20 @@ def run_cell(self, cell, cell_index=0):

return exec_reply, outs

def find_kernel_name(nb):
"""This is a utility that finds kernel names from notebook metadata.

Parameters
----------
nb : NotebookNode
The notebook that has a kernelspec defined in its metadata.

Returns
-------
kernel_name: str
The string representing the kernel name found in the metadata.
"""
return nb.metadata.get('kernelspec', {}).get('name', 'python')

def executenb(nb, cwd=None, km=None, **kwargs):
"""Execute a notebook's code, updating outputs within the notebook object.
Expand Down
32 changes: 32 additions & 0 deletions nbconvert/preprocessors/tests/files/UnicodePy3.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\u2603\n"
]
}
],
"source": [
"print('\u2603')"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
26 changes: 25 additions & 1 deletion nbconvert/preprocessors/tests/test_execute.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,9 @@
import pytest

from .base import PreprocessorTestsBase
from ..execute import ExecutePreprocessor, CellExecutionError, executenb
from ..execute import ExecutePreprocessor, CellExecutionError, executenb, find_kernel_name

from jupyter_client.kernelspec import KernelSpecManager

from nbconvert.filters import strip_ansi
from testpath import modified_env
Expand Down Expand Up @@ -151,6 +153,19 @@ def test_empty_path(self):
res['metadata']['path'] = ''
input_nb, output_nb = self.run_notebook(filename, {}, res)
self.assert_notebooks_equal(input_nb, output_nb)

@pytest.mark.xfail("python3" not in KernelSpecManager().find_kernel_specs(),
reason="requires a python3 kernelspec")
def test_empty_kernel_name(self):
"""Can kernel in nb metadata be found when an empty string is passed?

Note: this pattern should be discouraged in practice.
Passing in no kernel_name to ExecutePreprocessor is preferable.
"""
filename = os.path.join(current_dir, 'files', 'UnicodePy3.ipynb')
res = self.build_resources()
input_nb, output_nb = self.run_notebook(filename, {"kernel_name": ""}, res)
self.assert_notebooks_equal(input_nb, output_nb)

def test_disable_stdin(self):
"""Test disabling standard input"""
Expand Down Expand Up @@ -265,6 +280,15 @@ def test_custom_kernel_manager(self):
for method, call_count in expected:
self.assertNotEqual(call_count, 0, '{} was called'.format(method))

def test_find_kernel_name(self):
current_dir = os.path.dirname(__file__)
filename = os.path.join(current_dir, 'files', 'UnicodePy3.ipynb')

with io.open(filename) as f:
input_nb = nbformat.read(f, 4)

assert find_kernel_name(input_nb) == "python3"

def test_execute_function(self):
# Test the executenb() convenience API
current_dir = os.path.dirname(__file__)
Expand Down