I'd like to use a "switch/case" structure to decide which variable to assign a value to based on some parameter:
a, b = [init_val] * 2
# This doesn't exist in Python.
switch param
case 'a':
a = final_val
case 'b':
b = final_val
The dictionary method described in the question Replacements for switch statement in Python doesn't work here, since you can neither assign to a function call,
a, b = [init_val] * 2
switcher = {
'a': a,
'b': b
}
switcher.get(param) = final_val
nor change the value of a variable by storing it in a dictionary:
switcher[param] = final_val # switcher['a'] is only a copy of variable a
I could just stick to "if/elif", but since I have often seen that nice dictionary solution (as in the aforementioned question) for determining an output based on some parameter, I'm curious to see if there's a similar solution for determining which variable, out of a set of variables, to assign a value to.
switcher[param] = final_val
– Basilicataglobals()[switcher.get(param)] = final_val
, however, this is hackey, and really suggests that your "variables" should just be keys in their own dictionary, instead of clobbering the globals dictionary. Dynamically assigning to local variables is tougher in Python, and will be version / implementation dependent. Python 3 has made this a lot harder. Just don't do it. I hesitate to say "never", but I've never seen a good reason to. – Juntoreturn a, b
, I would end up withreturn var_dict['a'], var_dict['b']
? – Wertheimerdict
requires a single value lookup: it misses out on conditional expressions for selection of the appropriate assignment. Just a big miss in python. – Scutamatch/case
in _scala. Or any other language that supports assignment from arbitrary statements. – ScutaNone
in a separate (/awkward) line by itself – Scuta