如何在 Python Faker 中重置独特的方法

How to reset unique method in Python Faker

我正在使用 Faker 库为我正在构建的开源应用程序模拟重量训练数据 (https://github.com/TheNewThinkTank/Fitness-Tracker), 此模拟 (https://github.com/TheNewThinkTank/Fitness-Tracker/blob/main/src/simulate_data.py) 的一部分是从列表中进行 select 练习。每个选择的练习每次锻炼只能出现一次,我通过使用 faker 库中 Faker()unique 方法来保证这一点。当我模拟一次锻炼时,这很好用。但是,在尝试模拟不止一项锻炼时,我遇到了 faker.exceptions.UniquenessException: Got duplicated values after 1,000 iterations。 尝试在每次迭代后重置 unique 调用,但努力寻找正确的语法(fake.unique(reset=True) 给了我 TypeError: 'UniqueProxy' object is not callable)。这是我尝试过的方法(重现错误的最小示例):

from faker import Faker
from faker.providers import DynamicProvider

fake = Faker()

chest_exercises_provider = DynamicProvider(
    provider_name="chest_exercises",
    elements=["benchpress", "flys", "pullovers", "dips"],
)
fake.add_provider(chest_exercises_provider)

for workout in range(2):
    workout_chest_exercises = [fake.unique.chest_exercises() for _ in range(3)]  # <----- UniquenessException HERE !!

查看了 ,它很相似,但解决了确保唯一性和不重置 unique 方法调用的问题。 有什么方法可以在每次 for-loop 迭代后重置 unique 吗?或者任何其他解决它的想法(例如使用 random.sample 而不是 Faker 来练习 selection)?

单次锻炼的模拟数据结构如下:

{
  "date": "1994-11-28",
  "split": "back",
  "exercises": {
    "dead row": [{ "set no.": 1, "reps": 17, "weight": "5 kg" }],
    "chinups": [
      { "set no.": 1, "reps": 9, "weight": "92 kg" },
      { "set no.": 2, "reps": 11, "weight": "27 kg" },
      { "set no.": 3, "reps": 16, "weight": "85 kg" },
      { "set no.": 4, "reps": 19, "weight": "22 kg" },
      { "set no.": 5, "reps": 4, "weight": "65 kg" }
    ],
    "seated row": [
      { "set no.": 1, "reps": 19, "weight": "11 kg" },
      { "set no.": 2, "reps": 7, "weight": "24 kg" },
      { "set no.": 3, "reps": 10, "weight": "38 kg" },
      { "set no.": 4, "reps": 9, "weight": "70 kg" },
    ]
  }
}

您可以使用 .clear() 方法。
Have a look at the docs.