2

I have several variables, some of which I need to change on a certain condition.

test = 'foo'
a, b, c = None, None, None
if test == 'foo':
    a = 1
elif test == 'bar':
    b = 2
else:
    c = 3

I'd like to use the dict approach described here, but how can I modify it to change multiple variables? I want it to work like this:

options = {'foo': ('a',1), 'bar': ('b',2)}
reassign_variables(options,test, ('c',3))

Or can this not be done without creating a function and hard-coding all of the conditions in separately?

Community
  • 1
  • 1
lotrus28
  • 848
  • 2
  • 10
  • 19

4 Answers4

2

This will change variables in the module's global namespace

>>> options = {'foo': ('a',1), 'bar': ('b',2)}
>>> 
>>> def reassign_variables(options, test, default):
...     var, val = options.get(test, default)
...     globals()[var] = val
... 
>>> 
>>> a, b, c = None, None, None
>>> reassign_variables(options, "foo", ('c',3))
>>> a,b,c
(1, None, None)
>>> reassign_variables(options, "baz", ('c',3))
>>> a,b,c
(1, None, 3)
>>> 
tdelaney
  • 73,364
  • 6
  • 83
  • 116
0

Use the dict.update method like so, if I get you right:

test = 'foo'
options.update({test:('a',12)})
niklas
  • 2,887
  • 3
  • 38
  • 70
0

you can resign the values back to variables

a,b,c = None, None, None
options = {'foo': (1,b,c), 'bar': (a,1,c)}
default = (a,b,1)
test = 'foo'
a,b,c = options.get(test,default)
galaxyan
  • 5,944
  • 2
  • 19
  • 43
  • This is not scalable, as you would have to modify N-1 tuples every time and adding an extra one – Adirio Mar 20 '17 at 16:32
-1

According to this, you can access variables by name using globals(). Applying this method to the problem you are trying to solve, all you have to do is use your default value in the call to options.get

test = 'foo'
options = {'foo': ('a', 1), 'bar': ('b', 2)}
default = ('c', 3)
var_name, var_value = options.get(test, default)
globals()[var_name] = var_value

If the variables are members of an object, you can use setattr as explained here.

Community
  • 1
  • 1
  • It works, but the answer given by @tdelaney has better handling of the default case and gives it as a function as the OP suggested – Adirio Mar 20 '17 at 16:31
  • This provides a two-line solution that does not require the creation of a function – Pablo Gutierrez Marques Mar 20 '17 at 16:37
  • The 4 lines you had when I first commented weren't as elegant. (Edits are stored Pablo) Your current 2 lines are the same that in the function, so this answer now provides nothing new except from not using a function. The OP gave a function template the other answer complies with, while yours doesn't. – Adirio Mar 21 '17 at 13:44