google-cloud-spark-connect 2.1.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- google/cloud/managed_spark_connect/__init__.py +107 -0
- google/cloud/managed_spark_connect/_ipython.py +475 -0
- google/cloud/managed_spark_connect/client/__init__.py +14 -0
- google/cloud/managed_spark_connect/client/core.py +141 -0
- google/cloud/managed_spark_connect/client/proxy.py +269 -0
- google/cloud/managed_spark_connect/environment.py +190 -0
- google/cloud/managed_spark_connect/exceptions.py +47 -0
- google/cloud/managed_spark_connect/ide.py +1323 -0
- google/cloud/managed_spark_connect/pypi_artifacts.py +49 -0
- google/cloud/managed_spark_connect/session.py +1718 -0
- google/cloud/managed_spark_magics/__init__.py +45 -0
- google/cloud/managed_spark_magics/magics.py +123 -0
- google/cloud/managed_spark_magics/sparksql.py +1140 -0
- google_cloud_spark_connect-2.1.1.dist-info/METADATA +373 -0
- google_cloud_spark_connect-2.1.1.dist-info/RECORD +18 -0
- google_cloud_spark_connect-2.1.1.dist-info/WHEEL +5 -0
- google_cloud_spark_connect-2.1.1.dist-info/licenses/LICENSE +201 -0
- google_cloud_spark_connect-2.1.1.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
# Copyright 2024 Google LLC
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
import importlib.metadata
|
|
15
|
+
import importlib.util
|
|
16
|
+
import warnings
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _in_ipython() -> bool:
|
|
20
|
+
# Not environment.is_interactive(), which is also true in a plain
|
|
21
|
+
# `python -i` REPL, where the [interactive] extras do nothing.
|
|
22
|
+
try:
|
|
23
|
+
from IPython import get_ipython
|
|
24
|
+
|
|
25
|
+
return get_ipython() is not None
|
|
26
|
+
except Exception:
|
|
27
|
+
return False
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _install_extras(spark_extra: str) -> str:
|
|
31
|
+
"""The extras to recommend: also [interactive] inside IPython."""
|
|
32
|
+
return f"{spark_extra},interactive" if _in_ipython() else spark_extra
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _check_pyspark_version(pyspark_version: str) -> None:
|
|
36
|
+
from packaging.version import InvalidVersion, Version
|
|
37
|
+
|
|
38
|
+
try:
|
|
39
|
+
too_old = Version(pyspark_version).major < 4
|
|
40
|
+
except InvalidVersion:
|
|
41
|
+
# E.g. a custom build. Let the imports decide whether it works.
|
|
42
|
+
return
|
|
43
|
+
if too_old:
|
|
44
|
+
from .exceptions import UnsupportedPySparkVersionError
|
|
45
|
+
|
|
46
|
+
# pyspark-client starts at 4.0, so this is full pyspark: upgrade it in
|
|
47
|
+
# place with [spark] rather than adding pyspark-client next to it.
|
|
48
|
+
raise UnsupportedPySparkVersionError(
|
|
49
|
+
f"PySpark {pyspark_version} is installed, but "
|
|
50
|
+
"google-cloud-spark-connect requires PySpark 4.0 or later. "
|
|
51
|
+
"Upgrade it with: pip install -U "
|
|
52
|
+
f"'google-cloud-spark-connect[{_install_extras('spark')}]'"
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
# Needs nothing beyond the standard library, so it is safe to import before
|
|
57
|
+
# pyspark has been checked.
|
|
58
|
+
from .exceptions import PySparkNotInstalledError
|
|
59
|
+
|
|
60
|
+
try:
|
|
61
|
+
# pyspark.version first, so that an old pyspark gets a clear error rather
|
|
62
|
+
# than whichever ImportError session.py happens to hit first.
|
|
63
|
+
from pyspark.version import __version__ as _pyspark_version
|
|
64
|
+
|
|
65
|
+
_check_pyspark_version(_pyspark_version)
|
|
66
|
+
|
|
67
|
+
from .session import ManagedSparkSession
|
|
68
|
+
except PySparkNotInstalledError:
|
|
69
|
+
# From _check_pyspark_version(): already an ImportError with a clear
|
|
70
|
+
# message, not one to rewrite as "missing or incomplete".
|
|
71
|
+
raise
|
|
72
|
+
except ImportError as e:
|
|
73
|
+
# Only translate errors about pyspark itself (missing, a leftover
|
|
74
|
+
# namespace directory, a partial install), not about its dependencies,
|
|
75
|
+
# which pyspark already reports clearly.
|
|
76
|
+
if (e.name or "").partition(".")[0] != "pyspark":
|
|
77
|
+
raise
|
|
78
|
+
|
|
79
|
+
raise PySparkNotInstalledError(
|
|
80
|
+
f"PySpark is missing or incomplete in this environment ({e}). "
|
|
81
|
+
"Install it with: pip install "
|
|
82
|
+
f"'google-cloud-spark-connect[{_install_extras('client')}]'"
|
|
83
|
+
) from e
|
|
84
|
+
|
|
85
|
+
old_package_names = ["google-spark-connect", "dataproc-spark-connect"]
|
|
86
|
+
current_package_name = "google-cloud-spark-connect"
|
|
87
|
+
for old_package_name in old_package_names:
|
|
88
|
+
try:
|
|
89
|
+
importlib.metadata.distribution(old_package_name)
|
|
90
|
+
warnings.warn(
|
|
91
|
+
f"Package '{old_package_name}' is already installed in your environment. "
|
|
92
|
+
f"This might cause conflicts with '{current_package_name}'. "
|
|
93
|
+
f"Consider uninstalling '{old_package_name}' and only install '{current_package_name}'."
|
|
94
|
+
)
|
|
95
|
+
except Exception:
|
|
96
|
+
pass
|
|
97
|
+
|
|
98
|
+
# traitlets, like every other dependency of the interactive extras, only comes
|
|
99
|
+
# with the [interactive] extra. IPython depends on it, so without it there can
|
|
100
|
+
# be no shell and nothing to initialize.
|
|
101
|
+
if importlib.util.find_spec("traitlets") is not None:
|
|
102
|
+
# Only _init_extras: the ManagedSparkConnect configurable is looked up by
|
|
103
|
+
# class name (`c.ManagedSparkConnect...`), so it need not be importable
|
|
104
|
+
# from here, and would otherwise exist only when traitlets is installed.
|
|
105
|
+
from ._ipython import _init_extras
|
|
106
|
+
|
|
107
|
+
_init_extras()
|
|
@@ -0,0 +1,475 @@
|
|
|
1
|
+
# Copyright 2026 Google LLC
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
|
|
15
|
+
from dataclasses import dataclass, field
|
|
16
|
+
import importlib.util
|
|
17
|
+
import logging
|
|
18
|
+
import os
|
|
19
|
+
import sys
|
|
20
|
+
from typing import Any, Dict, List, Optional, Sequence, Set, Tuple
|
|
21
|
+
|
|
22
|
+
from traitlets import Bool, default, observe
|
|
23
|
+
from traitlets.config import Config, Configurable
|
|
24
|
+
|
|
25
|
+
logger = logging.getLogger(__name__)
|
|
26
|
+
|
|
27
|
+
ENV_ENABLE_EXTRAS = "MANAGED_SPARK_CONNECT_ENABLE_EXTRAS"
|
|
28
|
+
|
|
29
|
+
_ENV_FALSE_VALUES = frozenset(("0", "false", "no", "off"))
|
|
30
|
+
|
|
31
|
+
# Module that must be installed for explore_dataframe() to be injected.
|
|
32
|
+
_COLABSQLVIZ_MODULE = "google.colabsqlviz"
|
|
33
|
+
|
|
34
|
+
# (extension module, ((magic kind, magic name), ...)). Each extension is only
|
|
35
|
+
# loaded if its module is installed.
|
|
36
|
+
_EXTRAS_EXTENSIONS = (
|
|
37
|
+
(
|
|
38
|
+
"google.cloud.managed_spark_magics",
|
|
39
|
+
(("line", "dpip"), ("line", "sparksql"), ("cell", "sparksql")),
|
|
40
|
+
),
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _is_module_available(name: str) -> bool:
|
|
45
|
+
"""Whether `name` is installed, without importing it.
|
|
46
|
+
|
|
47
|
+
All of the extras' dependencies are optional (they come from the
|
|
48
|
+
[interactive] extra), so a module that isn't installed means that extra is
|
|
49
|
+
deliberately absent, not broken. Anything other than a clean "not found" is
|
|
50
|
+
reported as available so that the subsequent import surfaces the real error.
|
|
51
|
+
"""
|
|
52
|
+
try:
|
|
53
|
+
return importlib.util.find_spec(name) is not None
|
|
54
|
+
except ModuleNotFoundError:
|
|
55
|
+
# A parent package is missing.
|
|
56
|
+
return False
|
|
57
|
+
except Exception:
|
|
58
|
+
return True
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _is_env_extras_enabled() -> bool:
|
|
62
|
+
val = os.getenv(ENV_ENABLE_EXTRAS)
|
|
63
|
+
if val is None or not val.strip():
|
|
64
|
+
# Treat an empty/whitespace-only value the same as an unset variable,
|
|
65
|
+
# so that `MANAGED_SPARK_CONNECT_ENABLE_EXTRAS=` is not silently
|
|
66
|
+
# interpreted as "enabled".
|
|
67
|
+
return True
|
|
68
|
+
return val.strip().lower() not in _ENV_FALSE_VALUES
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
class ManagedSparkConnect(Configurable):
|
|
72
|
+
"""IPython configuration for google.cloud.managed_spark_connect extras."""
|
|
73
|
+
|
|
74
|
+
# No static default_value: the dynamic `_default_enable_extras` below
|
|
75
|
+
# always wins.
|
|
76
|
+
enable_extras = Bool(
|
|
77
|
+
help=(
|
|
78
|
+
"Whether to automatically load the installed interactive extras "
|
|
79
|
+
"(explore_dataframe, %dpip, %%sparksql)."
|
|
80
|
+
),
|
|
81
|
+
).tag(config=True)
|
|
82
|
+
|
|
83
|
+
def __init__(self, shell: Any = None, **kwargs: Any) -> None:
|
|
84
|
+
self._initialized = False
|
|
85
|
+
self._shell = shell
|
|
86
|
+
super().__init__(**kwargs)
|
|
87
|
+
self._initialized = True
|
|
88
|
+
|
|
89
|
+
@default("enable_extras")
|
|
90
|
+
def _default_enable_extras(self) -> bool:
|
|
91
|
+
return _is_env_extras_enabled()
|
|
92
|
+
|
|
93
|
+
@observe("enable_extras")
|
|
94
|
+
def _observe_enable_extras(self, change: Dict[str, Any]) -> None:
|
|
95
|
+
# Traitlets applies file-based config inside `super().__init__()`, and
|
|
96
|
+
# the resulting notification fires before the shell has been wired up.
|
|
97
|
+
# Skip it: `_init_extras` loads the extras once construction is done.
|
|
98
|
+
if not getattr(self, "_initialized", False):
|
|
99
|
+
return
|
|
100
|
+
shell = self._shell or self.parent
|
|
101
|
+
if shell is None:
|
|
102
|
+
return
|
|
103
|
+
if change["new"]:
|
|
104
|
+
_load_extras_for_shell(shell)
|
|
105
|
+
else:
|
|
106
|
+
_unload_extras_for_shell(shell)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
@dataclass
|
|
110
|
+
class _ShellExtrasState:
|
|
111
|
+
shell: Any
|
|
112
|
+
injected_explore_dataframe: Any = None
|
|
113
|
+
loaded_extensions: Set[str] = field(default_factory=set)
|
|
114
|
+
# Per extension we loaded, the (kind, name) magics it added. Magics that
|
|
115
|
+
# already existed under the same name were put back and are not listed.
|
|
116
|
+
added_magics: Dict[str, List[Tuple[str, str]]] = field(default_factory=dict)
|
|
117
|
+
config_instance: Optional[ManagedSparkConnect] = None
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
# Keyed by id() rather than being a WeakKeyDictionary. A weak key would not
|
|
121
|
+
# release anything here: the value reaches the key via
|
|
122
|
+
# `config_instance._shell` and traitlets' own `Configurable.parent`, and
|
|
123
|
+
# `InteractiveShell.__init__` hands a bound method to `atexit`, so a shell is
|
|
124
|
+
# retained for the life of the process regardless. `state.shell` is what makes
|
|
125
|
+
# id() keying safe, since CPython reuses addresses; see `_get_shell_state`.
|
|
126
|
+
_SHELL_STATES: Dict[int, _ShellExtrasState] = {}
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _get_shell_state(ip: Any) -> _ShellExtrasState:
|
|
130
|
+
shell_id = id(ip)
|
|
131
|
+
state = _SHELL_STATES.get(shell_id)
|
|
132
|
+
if state is None or state.shell is not ip:
|
|
133
|
+
state = _ShellExtrasState(shell=ip)
|
|
134
|
+
_SHELL_STATES[shell_id] = state
|
|
135
|
+
return state
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def _is_same_class(obj: Any, cls: type) -> bool:
|
|
139
|
+
"""Compares by module+qualname so that reloaded classes still match."""
|
|
140
|
+
obj_cls = type(obj)
|
|
141
|
+
return (
|
|
142
|
+
obj_cls.__module__ == cls.__module__
|
|
143
|
+
and obj_cls.__qualname__ == cls.__qualname__
|
|
144
|
+
)
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def _get_or_create_config(ip: Any) -> ManagedSparkConnect:
|
|
148
|
+
state = _get_shell_state(ip)
|
|
149
|
+
ip_config = getattr(ip, "config", None)
|
|
150
|
+
|
|
151
|
+
if state.config_instance is None:
|
|
152
|
+
parent = ip if isinstance(ip, Configurable) else None
|
|
153
|
+
config = (
|
|
154
|
+
ip_config
|
|
155
|
+
if (parent is None and isinstance(ip_config, Config))
|
|
156
|
+
else None
|
|
157
|
+
)
|
|
158
|
+
# Precedence is left entirely to traitlets: an explicit
|
|
159
|
+
# `c.ManagedSparkConnect.enable_extras` from the shell's config wins,
|
|
160
|
+
# otherwise `_default_enable_extras` consults the environment.
|
|
161
|
+
cfg = ManagedSparkConnect(shell=ip, parent=parent, config=config)
|
|
162
|
+
state.config_instance = cfg
|
|
163
|
+
else:
|
|
164
|
+
cfg = state.config_instance
|
|
165
|
+
cfg._shell = ip
|
|
166
|
+
|
|
167
|
+
configurables = getattr(ip, "configurables", None)
|
|
168
|
+
if isinstance(configurables, list):
|
|
169
|
+
# Remove any stale ManagedSparkConnect instances (e.g. across module
|
|
170
|
+
# reloads)
|
|
171
|
+
configurables[:] = [
|
|
172
|
+
c
|
|
173
|
+
for c in configurables
|
|
174
|
+
if c is cfg or not _is_same_class(c, ManagedSparkConnect)
|
|
175
|
+
]
|
|
176
|
+
if cfg not in configurables:
|
|
177
|
+
configurables.append(cfg)
|
|
178
|
+
|
|
179
|
+
return cfg
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def _import_explore_dataframe() -> Any:
|
|
183
|
+
"""Returns colabsqlviz's explore_dataframe(), or None if unavailable."""
|
|
184
|
+
try:
|
|
185
|
+
from google.colabsqlviz.explore_dataframe import explore_dataframe
|
|
186
|
+
|
|
187
|
+
return explore_dataframe
|
|
188
|
+
except Exception:
|
|
189
|
+
logger.debug("Failed to import explore_dataframe", exc_info=True)
|
|
190
|
+
return None
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def _safe_repr(value: Any, max_len: int = 60) -> str:
|
|
194
|
+
"""repr() that tolerates objects whose __repr__ raises."""
|
|
195
|
+
try:
|
|
196
|
+
val_repr = repr(value)
|
|
197
|
+
except Exception:
|
|
198
|
+
return f"<{type(value).__name__} with a failing __repr__>"
|
|
199
|
+
if len(val_repr) > max_len:
|
|
200
|
+
return f"{val_repr[:max_len]}..."
|
|
201
|
+
return val_repr
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def _print_extras_failure() -> None:
|
|
205
|
+
"""Tells the user something went wrong, without diagnosing what.
|
|
206
|
+
|
|
207
|
+
Every individual failure below is logged at debug level and otherwise
|
|
208
|
+
swallowed, which leaves a broken install looking exactly like extras being
|
|
209
|
+
switched off. One line, the same regardless of cause, is enough to point
|
|
210
|
+
somebody at the logs.
|
|
211
|
+
"""
|
|
212
|
+
print(
|
|
213
|
+
"\033[94m⚠️ [google.cloud.managed_spark_connect]\033[0m"
|
|
214
|
+
" Failed to load interactive extras."
|
|
215
|
+
" For details, enable debug logging and restart the kernel."
|
|
216
|
+
)
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def _shell_magics(ip: Any) -> Dict[str, Dict[str, Any]]:
|
|
220
|
+
magics_mgr = getattr(ip, "magics_manager", None)
|
|
221
|
+
magics = getattr(magics_mgr, "magics", None)
|
|
222
|
+
return magics if isinstance(magics, dict) else {}
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def _present_magics(
|
|
226
|
+
ip: Any, magics: Sequence[Tuple[str, str]]
|
|
227
|
+
) -> Dict[Tuple[str, str], Any]:
|
|
228
|
+
"""The subset of `magics` the shell already has, with their callables."""
|
|
229
|
+
shell_magics = _shell_magics(ip)
|
|
230
|
+
present = {}
|
|
231
|
+
for kind, name in magics:
|
|
232
|
+
kind_dict = shell_magics.get(kind)
|
|
233
|
+
if isinstance(kind_dict, dict) and name in kind_dict:
|
|
234
|
+
present[(kind, name)] = kind_dict[name]
|
|
235
|
+
return present
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def _is_from_module(fn: Any, module: str) -> bool:
|
|
239
|
+
"""Whether a registered magic was defined in `module` or a submodule."""
|
|
240
|
+
mod = getattr(fn, "__module__", None)
|
|
241
|
+
return isinstance(mod, str) and (
|
|
242
|
+
mod == module or mod.startswith(module + ".")
|
|
243
|
+
)
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def _is_extension_loaded(
|
|
247
|
+
ip: Any, ext_name: str, magics: Sequence[Tuple[str, str]]
|
|
248
|
+
) -> bool:
|
|
249
|
+
mod = sys.modules.get(ext_name)
|
|
250
|
+
if mod is not None and getattr(
|
|
251
|
+
getattr(mod, "__spec__", None), "_initializing", False
|
|
252
|
+
):
|
|
253
|
+
return True
|
|
254
|
+
|
|
255
|
+
ext_mgr = getattr(ip, "extension_manager", None)
|
|
256
|
+
loaded = getattr(ext_mgr, "loaded", None)
|
|
257
|
+
if isinstance(loaded, (set, dict, list, tuple)) and ext_name in loaded:
|
|
258
|
+
return True
|
|
259
|
+
|
|
260
|
+
# Every magic it would add is already there, so it has nothing to offer.
|
|
261
|
+
return len(_present_magics(ip, magics)) == len(magics)
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
def _print_extras_loaded(loaded: List[str]) -> None:
|
|
265
|
+
"""Lists the extras that were just loaded, in a single line.
|
|
266
|
+
|
|
267
|
+
Which extras get loaded depends on what happens to be installed, which the
|
|
268
|
+
user may not know (or may have forgotten), so name them explicitly rather
|
|
269
|
+
than leaving them to be discovered.
|
|
270
|
+
"""
|
|
271
|
+
names = ", ".join(f"\033[1m{name}\033[0m" for name in loaded)
|
|
272
|
+
print(
|
|
273
|
+
"\033[94m👉 [google.cloud.managed_spark_connect]\033[0m"
|
|
274
|
+
f" Loaded interactive extras: {names}."
|
|
275
|
+
" To disable: %config ManagedSparkConnect.enable_extras = False"
|
|
276
|
+
)
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def _magic_display_name(magic_kind: str, magic_name: str) -> str:
|
|
280
|
+
prefix = "%%" if magic_kind == "cell" else "%"
|
|
281
|
+
return f"{prefix}{magic_name}"
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
def _magics_display_names(magics: Sequence[Tuple[str, str]]) -> List[str]:
|
|
285
|
+
"""Display names, listing a magic that is both line and cell once."""
|
|
286
|
+
return [
|
|
287
|
+
_magic_display_name(kind, name)
|
|
288
|
+
for kind, name in magics
|
|
289
|
+
if not (kind == "line" and ("cell", name) in magics)
|
|
290
|
+
]
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
def _load_extras_for_shell(ip: Any) -> None:
|
|
294
|
+
state = _get_shell_state(ip)
|
|
295
|
+
target_name = "explore_dataframe"
|
|
296
|
+
failed = False
|
|
297
|
+
# Only what this call loaded; anything that was already present, whether
|
|
298
|
+
# from us or the user, is not news.
|
|
299
|
+
loaded: List[str] = []
|
|
300
|
+
|
|
301
|
+
# 1. Inject explore_dataframe from google-colabsqlviz
|
|
302
|
+
try:
|
|
303
|
+
user_ns = getattr(ip, "user_ns", None)
|
|
304
|
+
if not _is_module_available(_COLABSQLVIZ_MODULE):
|
|
305
|
+
logger.debug(
|
|
306
|
+
"Not injecting %s: %s is not installed",
|
|
307
|
+
target_name,
|
|
308
|
+
_COLABSQLVIZ_MODULE,
|
|
309
|
+
)
|
|
310
|
+
elif isinstance(user_ns, dict):
|
|
311
|
+
if (
|
|
312
|
+
state.injected_explore_dataframe is not None
|
|
313
|
+
and user_ns.get(target_name) is state.injected_explore_dataframe
|
|
314
|
+
):
|
|
315
|
+
pass
|
|
316
|
+
elif target_name not in user_ns:
|
|
317
|
+
from google.colabsqlviz.explore_dataframe import (
|
|
318
|
+
explore_dataframe,
|
|
319
|
+
)
|
|
320
|
+
|
|
321
|
+
ip.push({target_name: explore_dataframe})
|
|
322
|
+
state.injected_explore_dataframe = explore_dataframe
|
|
323
|
+
loaded.append(f"{target_name}()")
|
|
324
|
+
else:
|
|
325
|
+
current_val = user_ns[target_name]
|
|
326
|
+
ours = _import_explore_dataframe()
|
|
327
|
+
if ours is not None and current_val is ours:
|
|
328
|
+
# Already bound to the exact function we would have
|
|
329
|
+
# injected, e.g. because the user imported it themselves.
|
|
330
|
+
# Warning about that would be pure noise.
|
|
331
|
+
pass
|
|
332
|
+
else:
|
|
333
|
+
val_repr = _safe_repr(current_val)
|
|
334
|
+
print(
|
|
335
|
+
"\033[94m⚠️ [google.cloud.managed_spark_connect]\033[0m"
|
|
336
|
+
f" Did not inject \033[1m{target_name}()\033[0m"
|
|
337
|
+
f" because it is already defined as: {val_repr}"
|
|
338
|
+
)
|
|
339
|
+
except Exception:
|
|
340
|
+
logger.debug(
|
|
341
|
+
"Failed to inject %s into IPython user_ns",
|
|
342
|
+
target_name,
|
|
343
|
+
exc_info=True,
|
|
344
|
+
)
|
|
345
|
+
failed = True
|
|
346
|
+
|
|
347
|
+
# 2. Load magic extensions
|
|
348
|
+
ext_mgr = getattr(ip, "extension_manager", None)
|
|
349
|
+
if ext_mgr is not None and hasattr(ext_mgr, "load_extension"):
|
|
350
|
+
for ext_name, magics in _EXTRAS_EXTENSIONS:
|
|
351
|
+
try:
|
|
352
|
+
if ext_name in state.loaded_extensions or (
|
|
353
|
+
_is_extension_loaded(ip, ext_name, magics)
|
|
354
|
+
):
|
|
355
|
+
continue
|
|
356
|
+
if not _is_module_available(ext_name):
|
|
357
|
+
logger.debug(
|
|
358
|
+
"Not loading IPython extension %s: not installed",
|
|
359
|
+
ext_name,
|
|
360
|
+
)
|
|
361
|
+
continue
|
|
362
|
+
# A magic of the same name from somewhere else (e.g. the
|
|
363
|
+
# sparksql-magic package) must survive our extension loading.
|
|
364
|
+
existing = _present_magics(ip, magics)
|
|
365
|
+
res = ext_mgr.load_extension(ext_name)
|
|
366
|
+
if res is None:
|
|
367
|
+
shell_magics = _shell_magics(ip)
|
|
368
|
+
for (kind, name), fn in existing.items():
|
|
369
|
+
shell_magics.setdefault(kind, {})[name] = fn
|
|
370
|
+
added = [m for m in magics if m not in existing]
|
|
371
|
+
state.loaded_extensions.add(ext_name)
|
|
372
|
+
state.added_magics[ext_name] = added
|
|
373
|
+
loaded.extend(_magics_display_names(added))
|
|
374
|
+
except Exception:
|
|
375
|
+
logger.debug(
|
|
376
|
+
"Failed to load IPython extension %s",
|
|
377
|
+
ext_name,
|
|
378
|
+
exc_info=True,
|
|
379
|
+
)
|
|
380
|
+
failed = True
|
|
381
|
+
|
|
382
|
+
if loaded:
|
|
383
|
+
_print_extras_loaded(loaded)
|
|
384
|
+
if failed:
|
|
385
|
+
_print_extras_failure()
|
|
386
|
+
|
|
387
|
+
|
|
388
|
+
def _unload_extras_for_shell(ip: Any) -> None:
|
|
389
|
+
state = _get_shell_state(ip)
|
|
390
|
+
target_name = "explore_dataframe"
|
|
391
|
+
|
|
392
|
+
# 1. Remove explore_dataframe only if we injected it and it wasn't overwritten
|
|
393
|
+
try:
|
|
394
|
+
if state.injected_explore_dataframe is not None:
|
|
395
|
+
user_ns = getattr(ip, "user_ns", None)
|
|
396
|
+
if (
|
|
397
|
+
isinstance(user_ns, dict)
|
|
398
|
+
and user_ns.get(target_name) is state.injected_explore_dataframe
|
|
399
|
+
):
|
|
400
|
+
del user_ns[target_name]
|
|
401
|
+
state.injected_explore_dataframe = None
|
|
402
|
+
except Exception:
|
|
403
|
+
logger.debug(
|
|
404
|
+
"Failed to remove %s from IPython user_ns",
|
|
405
|
+
target_name,
|
|
406
|
+
exc_info=True,
|
|
407
|
+
)
|
|
408
|
+
|
|
409
|
+
# 2. Unload only the extensions that we loaded
|
|
410
|
+
ext_mgr = getattr(ip, "extension_manager", None)
|
|
411
|
+
loaded = getattr(ext_mgr, "loaded", None)
|
|
412
|
+
|
|
413
|
+
for ext_name, magics in _EXTRAS_EXTENSIONS:
|
|
414
|
+
if ext_name in state.loaded_extensions:
|
|
415
|
+
added = state.added_magics.pop(ext_name, ())
|
|
416
|
+
# Magics from this extension that were already present before we
|
|
417
|
+
# loaded (e.g. from `%load_ext ...sparksql`) must survive unload.
|
|
418
|
+
preserved = _present_magics(
|
|
419
|
+
ip, [m for m in magics if m not in added]
|
|
420
|
+
)
|
|
421
|
+
try:
|
|
422
|
+
if ext_mgr is not None and hasattr(ext_mgr, "unload_extension"):
|
|
423
|
+
ext_mgr.unload_extension(ext_name)
|
|
424
|
+
except Exception:
|
|
425
|
+
logger.debug(
|
|
426
|
+
"Failed to unload IPython extension %s",
|
|
427
|
+
ext_name,
|
|
428
|
+
exc_info=True,
|
|
429
|
+
)
|
|
430
|
+
try:
|
|
431
|
+
shell_magics = _shell_magics(ip)
|
|
432
|
+
for (kind, name), fn in preserved.items():
|
|
433
|
+
shell_magics.setdefault(kind, {})[name] = fn
|
|
434
|
+
for kind, name in added:
|
|
435
|
+
kind_dict = shell_magics.get(kind)
|
|
436
|
+
if isinstance(kind_dict, dict) and _is_from_module(
|
|
437
|
+
kind_dict.get(name), ext_name
|
|
438
|
+
):
|
|
439
|
+
del kind_dict[name]
|
|
440
|
+
if isinstance(loaded, set):
|
|
441
|
+
loaded.discard(ext_name)
|
|
442
|
+
except Exception:
|
|
443
|
+
logger.debug(
|
|
444
|
+
"Failed to clean up magics for extension %s",
|
|
445
|
+
ext_name,
|
|
446
|
+
exc_info=True,
|
|
447
|
+
)
|
|
448
|
+
state.loaded_extensions.discard(ext_name)
|
|
449
|
+
|
|
450
|
+
|
|
451
|
+
def _init_extras() -> None:
|
|
452
|
+
"""Initialize interactive extras on package import unless opted out."""
|
|
453
|
+
ip = None
|
|
454
|
+
try:
|
|
455
|
+
from IPython import get_ipython
|
|
456
|
+
|
|
457
|
+
ip = get_ipython()
|
|
458
|
+
if ip is None:
|
|
459
|
+
return
|
|
460
|
+
|
|
461
|
+
# `cfg.enable_extras` already folds in both the environment variable
|
|
462
|
+
# (via the trait's dynamic default) and any explicit configuration, and
|
|
463
|
+
# it is the same value `%config` toggles later, so it is the only thing
|
|
464
|
+
# that should be consulted here.
|
|
465
|
+
cfg = _get_or_create_config(ip)
|
|
466
|
+
if cfg.enable_extras:
|
|
467
|
+
_load_extras_for_shell(ip)
|
|
468
|
+
except Exception:
|
|
469
|
+
logger.debug(
|
|
470
|
+
"Failed to initialize IPython extras on import", exc_info=True
|
|
471
|
+
)
|
|
472
|
+
if ip is not None:
|
|
473
|
+
# Only worth saying inside a shell: outside one there are no extras
|
|
474
|
+
# to miss, and printing would be noise in ordinary scripts.
|
|
475
|
+
_print_extras_failure()
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
# Copyright 2024 Google LLC
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
from .core import ManagedSparkChannelBuilder
|