python - How to don't evaluate both functions in list choice if/else alternative? -
i'm in situation :
- the functions contents created dynamically in string before being evaluated,
- i don't want use
if test: dosomething else: dosomethingelse
compose content because users can change part of string content, , don't want them have manage spaces between math expression in conditionnal statement.
so, use following list tip: [dosomethingelse, dosomething][ test ]
, (true/false answser test gives me dosomething/dosomethingelse).
the solution works correctly dosomething , dosomethingelse are both evaluated before test check, , i'm interested in evaluating one. (i'm in severe time constraint situation).
is there way evaluate 1 function in 1 line ?
here, main steps of code. 'dependencies' listed here, managed in original program.
create unique fun_id
def gen_id(): s = 10000 while s: yield s s += 1 fun_ticket = gen_id()
fun descriptions (name, args, expression, id)
from collections import defaultdict d= defaultdict(lambda :defaultdict()) d["dosomething"]["args"] = set(["arga","argb"]) d["dosomething"]["exp"] = "return arga + argb" d["dosomething"]["id"] = "f_%d"%(fun_ticket.next()) d["dosomethingelse"]["args"] = set(["argx","argy","argz"]) d["dosomethingelse"]["exp"] = "return argx + argy+ argz" d["dosomethingelse"]["id"] = "f_%d"%(fun_ticket.next()) d["dochoice"]["args"] = set(["arge","argf"]) d["dochoice"]["exp"] = "return [dosomethingelse, dosomething][arge > 0] + argf" d["dochoice"]["id"] = "f_%d"%(fun_ticket.next())
prepare dochoice function evaluated.
dependencies = ('dosomething', 'dosomethingelse', 'dochoice') allargs = set().union(*[d[x]["args"] x in dependencies]) funchoice = 'def %s(%s): %s'%(d['dochoice']['id'],",".join(allargs),d['dochoice']["exp"])
result: funchoice string :
def f_10002(argx,argy,argz,arga,argb,arge,argf): return [f_10001(argx,argy,argz), f_10000(arga,argb)][arge > 0] + argf
here problem: funchoice evaluation eval dosomething and dosomethingelse. there way eval 1 without using if else (and space management problems in string..) ?
dosomething if test else dosomethingelse
only 1 of dosomething
, dosomethingelse
evaluated depending on outcome of test
. quoting documentation:
the expression
x if c else y
first evaluates condition, c (not x); if c true, x evaluated , value returned; otherwise, y evaluated , value returned.
adapting code:
d["dochoice"]["exp"] = "return (dosomething if arge > 0 else dosomethingelse) + argf"
Comments
Post a Comment