Skip to content

Commit c0e31a3

Browse files
committed
Automatically load IPython extension
1 parent d001fe6 commit c0e31a3

File tree

1 file changed

+34
-1
lines changed

1 file changed

+34
-1
lines changed

pysrc/juliacall/__init__.py

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -248,8 +248,41 @@ def jlstr(x):
248248
"PYTHON_JULIACALL_HANDLE_SIGNALS=no."
249249
)
250250

251-
init()
251+
# Next, automatically load the juliacall extension if we are in a Jupyter notebook
252+
CONFIG['autoload_extensions'] = choice('autoload_extensions', ['yes', 'no'])[0]
253+
if CONFIG['autoload_extensions'] in {'yes', None}:
254+
try:
255+
# Get IPython `InteractiveShell` instance
256+
get_ipython = sys.modules['IPython'].get_ipython
257+
258+
# This line is a check for the IPython kernel being loaded to the
259+
# interactive shell, so that we don't activate for other types of
260+
# interactive shells).
261+
if 'IPKernelApp' not in get_ipython().config:
262+
raise ImportError('console')
263+
264+
if CONFIG['autoload_extensions'] is None:
265+
# Only let the user know if it was not explicitly set
266+
print(
267+
"Detected Jupyter notebook. Loading juliacall extension. To disable, you can either "
268+
"set the environment variable PYTHON_JULIACALL_AUTOLOAD_EXTENSIONS=no or pass the "
269+
"command line argument '-X juliacall-autoload-extensions=no'. Inside Jupyter, you can "
270+
"do this with `import os; os.environ['PYTHON_JULIACALL_AUTOLOAD_EXTENSIONS'] = 'no'`. "
271+
"To suppress this message, set PYTHON_JULIACALL_AUTOLOAD_EXTENSIONS=yes."
272+
)
273+
274+
load_ipython_extension(get_ipython())
275+
except Exception as e:
276+
if CONFIG['autoload_extensions'] == 'yes':
277+
# Only warn if the user explicitly requested the extension to be loaded
278+
warnings.warn(
279+
"Could not load juliacall extension in Jupyter notebook: " + str(e)
280+
)
281+
pass
282+
252283

253284
def load_ipython_extension(ip):
254285
import juliacall.ipython
255286
juliacall.ipython.load_ipython_extension(ip)
287+
288+
init()

0 commit comments

Comments
 (0)