【问题标题】:Is uuid.uuid4() safe to use on Windows with multiprocessing?uuid.uuid4() 在 Windows 上使用多处理安全吗?
【发布时间】:2022-08-10 05:30:27
【问题描述】:

我在 Python (Python 3.10) 中运行一个多进程程序

我正在使用 uuid 库创建一个随机 uuid (uuid.uuid4()) uuid 文档提供了一个 \'is_safe\' 方法,该方法假设告诉开发人员创建的 uuid 在多进程环境中是否可以安全使用。 see link

在 Windows 上运行时,\'is_safe\' 方法返回 \'SafeUUID.unknown\' 有谁知道 Windows 是否生成安全的 UUID?

    标签: python windows thread-safety python-multiprocessing uuid


    【解决方案1】:

    我和你有同样的问题,我不知道答案。

    我有一些这样的代码

    rand_id = uuid.uuid4()
    assert rand_id.is_safe == uuid.SafeUUID.safe, f"uuid.uuid4() returned a UUID object with is_safe = {rand_id.is_safe} != uuid.SafeUUID.safe"
    

    这是因为 uuid4 返回 SafeUUID.unknown 而不是该断言。

    我可以补充的是,这种行为似乎与uuid4 紧密相关。这是它的实现的样子(在我当前的 venv 中使用的 Python 3.8 中):

    def uuid4():
        """Generate a random UUID."""
        return UUID(bytes=os.urandom(16), version=4)
    

    关键在于,如果在 UUID 构造函数调用中未能提供 is_safe 参数,则将使用其默认值 SafeUUID.unknown

    这就解释了为什么我们会看到我们在 Windows 上所做的行为(可能还有其他所有操作系统)。

    如果有人了解为什么uuid4 的编码方式是这样的,如果它在更高版本的 Python 中发生变化等等,我很想知道。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-01
      • 1970-01-01
      • 2021-07-01
      • 2017-05-28
      • 2011-01-05
      • 2011-08-08
      • 2019-12-29
      • 1970-01-01
      相关资源
      最近更新 更多