Can I Conditionally Choose What Variable I Assign A Value To?
Solution 1:
Well theoretically you could do something like this, if both variables are already defined:
var1, var2 = (value, var2) ifbooleanCheck()else (var1, value)
Not saying that you should do it, though.
Solution 2:
Since the use case is assigning to the correct side of a binary tree, I assume the assignment targets are actually attributes of some tree node, and the usual code would be
if condition:
node.left =valueelse
node.right =value
This code could be replaced by
setattr(node, "left"if condition else"right", value)
or alternatively
vars(node)["left"if condition else"right"] = value
It could be replaced by this, but it really shouldn't.
Solution 3:
It's not very good form to use locals
or globals
in this way (confusing, not often used, hard to debug, terrible performance), but it can be done:
varname = 'a'if some_condition else'b'locals()[varname] = value # or globals()printlocals()[varname] # or globals()
I think the real challenge here is to resist seemingly "fancy" or "creative" code and write code that others will understand immediately. Not to mention yourself if you have to come back to it later. But it is worth it to know what funky code (as in old cheese) looks like.
Solution 4:
Unlike locals()
, globals()
is documented to be updateable (as it returns the __dict__
of the current module). I routinely use vars()
in the global scope - which is the same in that case - to reduce code duplication:
for v,ar in('a',x),('b',y): vars()[v]=fn(ar)
For some others objects (like the current class/instance), __dict__
's members are accessible as syntactic variables, too:
classC:
def__init__(self,a,b):
vars(self).update(v,locals()[v] for v in'a','b')
do_something(self.a)
Do note, however, that:
- These "syntactic references" reduce code maintainability - as they are harder to find - and thus will likely upset code checking tools like
pylint
. - a need to use variables in such a way typically signifies an attempt to use a scope as a
dict
: such variables tend to be "homogenous" in some way, asking for being used in array operations, and thus should probably be combined into a dedicated container instead.- this goes double when variable names are autogenerated - and also runs the risk of collisions. See also How can you dynamically create variables via a while loop? on this.
Post a Comment for "Can I Conditionally Choose What Variable I Assign A Value To?"