PAYATHON 2026

如何在 external Python library 中调用 mssparkutils?

技术老齐

结论

业务逻辑可以放在 external Python library 中,但该 library 的运行时代码不要直接导入 dummy-notebookutils。

这里涉及两个机制:

  • Synapse notebook 会把 mssparkutils 注入 notebook 的命名空间。external library 有自己的模块命名空间,因此看不到 notebook 中的全局变量。
  • dummy-notebookutils 与 Synapse 运行环境使用相同的 notebookutils 导入路径。如果将它打包或安装到 Synapse 环境中,它可能覆盖实际实现,或比实际实现更早被加载,导致 getPropertiesAll() 返回 dummy 提供的空字符串。

更稳妥的办法是使用依赖注入,由 notebook 将真实的 mssparkutils 传给 library。只需给用到该对象的函数增加参数,或者在 library 初始化时统一注册一次,不必把整个代码库改成一个大 class。

为什么会出现 NameError

每个 Python 模块都有自己的全局命名空间。假设 notebook 中有以下代码:

mssparkutils.fs.ls("abfss://...")

这里的 mssparkutils 只存在于当前 notebook 的命名空间中。library 中的函数不会沿调用栈查找 notebook 的全局变量,因此下面的 external library 代码无法使用 notebook 自动注入的对象:

def copy_file_to_folder(path_to_file, path_to_folder):
    mssparkutils.fs.cp(path_to_file, path_to_folder)

如果 library 没有自行定义或导入 mssparkutils,调用时会出现:

NameError: name 'mssparkutils' is not defined

如果改为在 library 中导入:

from notebookutils import mssparkutils

则可能拿到 dummy-notebookutils 提供的占位对象。空字符串是 dummy 实现的返回结果,不代表 Synapse linked service 返回了空数据。

推荐方案:按函数传入依赖

只需修改实际使用 mssparkutils 的函数:

from pathlib import Path
from typing import Any


def copy_file_to_folder(
    path_to_file: str,
    path_to_folder: str,
    notebook_utils: Any,
) -> str:
    notebook_utils.fs.cp(
        path_to_file,
        f"file:{path_to_folder}",
    )

    return str(
        Path(path_to_folder) / Path(path_to_file).name
    )

在 Synapse notebook 中调用:

from my_library.files import copy_file_to_folder

result = copy_file_to_folder(
    path_to_file=source_path,
    path_to_folder=target_folder,
    notebook_utils=mssparkutils,
)

读取 linked service 属性时也可以传入同一个对象:

import json
from typing import Any


def get_linked_service_properties(
    linked_service: str,
    notebook_utils: Any,
) -> dict:
    raw_properties = (
        notebook_utils.credentials
        .getPropertiesAll(linked_service)
    )

    if not raw_properties:
        raise RuntimeError(
            f"Linked service {linked_service!r} returned empty properties"
        )

    return json.loads(raw_properties)

Notebook 中的调用方式如下:

from my_library.credentials import get_linked_service_properties

props = get_linked_service_properties(
    linked_service,
    notebook_utils=mssparkutils,
)

这种改法不会影响 library 的整体结构,也不需要创建一个容纳全部业务逻辑的大 class。

本地 unit testing

本地测试不需要安装或调用真正的 mssparkutils,使用 mock 就能验证调用参数和返回值:

from unittest.mock import Mock

from my_library.files import copy_file_to_folder


def test_copy_file_to_folder():
    notebook_utils = Mock()

    result = copy_file_to_folder(
        path_to_file="/tmp/input.csv",
        path_to_folder="/tmp/output",
        notebook_utils=notebook_utils,
    )

    notebook_utils.fs.cp.assert_called_once_with(
        "/tmp/input.csv",
        "file:/tmp/output",
    )

    assert result == "/tmp/output/input.csv"

credentials 逻辑也可以这样测试:

from unittest.mock import Mock

from my_library.credentials import get_linked_service_properties


def test_get_linked_service_properties():
    notebook_utils = Mock()
    notebook_utils.credentials.getPropertiesAll.return_value = (
        '{"server": "example", "database": "analytics"}'
    )

    result = get_linked_service_properties(
        "example-linked-service",
        notebook_utils,
    )

    assert result == {
        "server": "example",
        "database": "analytics",
    }

与“什么都不做”的 dummy 相比,mock 更容易暴露问题。它可以检查 fs.cp() 是否被调用、调用参数是否正确,还能验证代码是否妥善处理了空响应。

如果不想给每个函数增加参数

可以在 library 中增加一个小型运行时注册模块,由 notebook 在启动时注入一次:

# my_library/runtime.py

from typing import Any, Optional

_notebook_utils: Optional[Any] = None


def configure_notebook_utils(notebook_utils: Any) -> None:
    global _notebook_utils
    _notebook_utils = notebook_utils


def get_notebook_utils() -> Any:
    if _notebook_utils is None:
        raise RuntimeError(
            "Notebook utilities have not been configured"
        )

    return _notebook_utils

业务代码从该模块获取对象:

# my_library/files.py

from pathlib import Path

from .runtime import get_notebook_utils


def copy_file_to_folder(
    path_to_file: str,
    path_to_folder: str,
) -> str:
    notebook_utils = get_notebook_utils()

    notebook_utils.fs.cp(
        path_to_file,
        f"file:{path_to_folder}",
    )

    return str(
        Path(path_to_folder) / Path(path_to_file).name
    )

Notebook 启动时完成注册:

from my_library.runtime import configure_notebook_utils

configure_notebook_utils(mssparkutils)

后续可以继续使用原来的函数签名:

from my_library.files import copy_file_to_folder

result = copy_file_to_folder(source_path, target_folder)

这种方式对现有代码的改动较少,但会引入模块级状态。每个测试都要重新配置,以免测试之间相互影响。如果调用链不深,直接传递参数通常更清楚。

dummy-notebookutils 应该如何使用

如果需要保留 dummy-notebookutils,应将它限制为本地开发依赖。不要把它列为 library 的生产依赖,也不要随 wheel 或 Synapse environment 一起部署。

例如,可以在 pyproject.toml 中单独声明开发依赖:

[project.optional-dependencies]
dev = [
    "dummy-notebookutils",
    "pytest",
]

本地安装:

pip install -e ".[dev]"

library 的生产代码中不应再有以下导入:

from notebookutils import mssparkutils

如果测试确实需要 dummy,只在测试代码中导入:

# tests only
from notebookutils import mssparkutils

能否通过打包配置确保 dummy 不会进入 Synapse,取决于当前的依赖安装和发布流程。由于它和 Synapse 实现使用相同的 notebookutils 模块名,始终存在导入冲突的风险。使用 mock 或自行编写 fake 通常更安全。

不建议使用的写法

不要在业务模块中通过捕获异常来切换真实实现和 dummy:

try:
    from notebookutils import mssparkutils
except ImportError:
    from some_dummy_package import mssparkutils

如果 dummy 已经提供了名为 notebookutils 的模块,第一次导入就会成功,代码也就无法判断得到的是 Synapse 实现还是 dummy。

也不要等 json.loads() 自行暴露空响应。先检查返回值,得到的异常会更有用:

raw = mssparkutils.credentials.getPropertiesAll(linked_service)

if not raw:
    raise RuntimeError(
        f"No properties returned for {linked_service!r}"
    )

props = json.loads(raw)

建议的代码边界

代码可以分为两层:

  • 普通数据处理、路径计算和 JSON 转换使用纯 Python,不依赖 Synapse。
  • 文件系统、credentials 和 notebook 调用等平台操作,通过函数参数或小型 adapter 注入。

按这种方式组织后,Synapse 可以使用真实的 mssparkutils,本地测试则使用 mock,同时还能避免 dummy-notebookutils 干扰 Synapse 的运行时对象。

备注:内容仅供参考。