refactor: make_random

* Simplify logic
* Add typing
This commit is contained in:
Gavin D'souza 2022-08-11 14:55:40 +05:30 committed by gavin
parent 8d19a815b3
commit 605e5a3010

View file

@ -1,7 +1,11 @@
import random
from typing import TYPE_CHECKING
import frappe
if TYPE_CHECKING:
from frappe.model.document import Document
settings = frappe._dict(
prob={
"default": {"make": 0.6, "qty": (1, 5)},
@ -9,7 +13,7 @@ settings = frappe._dict(
)
def add_random_children(doc, fieldname, rows, randomize, unique=None):
def add_random_children(doc: "Document", fieldname: str, rows, randomize: dict, unique=None):
nrows = rows
if rows > 1:
nrows = random.randrange(1, rows)
@ -29,15 +33,13 @@ def add_random_children(doc, fieldname, rows, randomize, unique=None):
doc.append(fieldname, d)
def get_random(doctype, filters=None, doc=False):
def get_random(doctype: str, filters: dict = None, doc: bool = False):
condition = []
if filters:
for key, val in filters.items():
condition.append("{}='{}'".format(key, str(val).replace("'", "'")))
if condition:
condition = " where " + " and ".join(condition)
else:
condition = ""
condition.extend(
"{}='{}'".format(key, str(val).replace("'", "'")) for key, val in filters.items()
)
condition = " where " + " and ".join(condition) if condition else ""
out = frappe.db.multisql(
{
@ -54,13 +56,12 @@ def get_random(doctype, filters=None, doc=False):
if doc and out:
return frappe.get_doc(doctype, out)
else:
return out
return out
def can_make(doctype):
def can_make(doctype: str) -> bool:
return random.random() < settings.prob.get(doctype, settings.prob["default"])["make"]
def how_many(doctype):
def how_many(doctype: str) -> int:
return random.randrange(*settings.prob.get(doctype, settings.prob["default"])["qty"])