Determine the most specific context that we're in. Returns: _CONTEXT_COLAB: If in Colab with an IPython notebook context. _CONTEXT_IPYTHON: If not in Colab, but we are in an IPython notebook context (e.g., from running `jupyter notebook` at the command line). _
()
| 38 | |
| 39 | |
| 40 | def _get_context(): |
| 41 | """Determine the most specific context that we're in. |
| 42 | |
| 43 | Returns: |
| 44 | _CONTEXT_COLAB: If in Colab with an IPython notebook context. |
| 45 | _CONTEXT_IPYTHON: If not in Colab, but we are in an IPython notebook |
| 46 | context (e.g., from running `jupyter notebook` at the command |
| 47 | line). |
| 48 | _CONTEXT_NONE: Otherwise (e.g., by running a Python script at the |
| 49 | command-line or using the `ipython` interactive shell). |
| 50 | """ |
| 51 | # In Colab, the `google.colab` module is available, but the shell |
| 52 | # returned by `IPython.get_ipython` does not have a `get_trait` |
| 53 | # method. |
| 54 | try: |
| 55 | import google.colab # noqa: F401 |
| 56 | import IPython |
| 57 | except ImportError: |
| 58 | pass |
| 59 | else: |
| 60 | if IPython.get_ipython() is not None: |
| 61 | # We'll assume that we're in a Colab notebook context. |
| 62 | return _CONTEXT_COLAB |
| 63 | |
| 64 | # In an IPython command line shell or Jupyter notebook, we can |
| 65 | # directly query whether we're in a notebook context. |
| 66 | try: |
| 67 | import IPython |
| 68 | except ImportError: |
| 69 | pass |
| 70 | else: |
| 71 | ipython = IPython.get_ipython() |
| 72 | if ipython is not None and ipython.has_trait("kernel"): |
| 73 | return _CONTEXT_IPYTHON |
| 74 | |
| 75 | # Otherwise, we're not in a known notebook context. |
| 76 | return _CONTEXT_NONE |
| 77 | |
| 78 | |
| 79 | def load_ipython_extension(ipython): |