Is it possible to conditionally choose which variable I assign?

I know you can do such things in Python:

var = value1 if( booleanCheck() ) else value2 

What do I want to know if I can conditionally choose which var I put in a value with a similar structure?

something like that:

 (var1 if( booleanCheck() ) else var2) = value 

In my case, specifically, I am trying to assign the node child to the right side in the binary search tree, I know that I can just make a normal if block, but I was trying to challenge myself using minimal space.

+3
source share
4 answers

Well, theoretically, you could do something like this if both variables are already defined:

 var1, var2 = (value, var2) if booleanCheck() else (var1, value) 

Not to mention that you have to do this.

+4
source

Since the use case assigns the right side of the binary tree, I assume that the target assignments are actually attributes of some node tree, and the usual code would be

 if condition: node.left = value else node.right = value 

This code can be replaced by

 setattr(node, "left" if condition else "right", value) 

or alternatively

 vars(node)["left" if condition else "right"] = value 

It can be replaced by this, but it really should not be.

+2
source

This is not a good form for using 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() print locals()[varname] # or globals() 

I believe that the real problem is to confront the seemingly “bizarre” or “creative” code and write code that others will immediately understand. Not to mention yourself if you have to return to it later. But you should know what the funk code actually looks like (like in an old cheese).

+1
source

Unlike locals() , globals() documented as updatable (since it returns __dict__ current module). I usually use vars() in the global scope - the same thing in this case - to reduce code duplication:

 for v,ar in ('a',x),('b',y): vars()[v]=fn(ar) 

For some other objects (e.g. current class / instance), __dict__ members __dict__ also available as syntax variables:

 class C: def __init__(self,a,b): vars(self).update(v,locals()[v] for v in 'a','b') do_something(self.a) 

Please note, however, that:

  • These “syntax links” reduce the code's resiliency — since they are harder to find — and therefore code checking tools like pylint will probably be broken.
  • the need to use variables in this way usually means trying to use a region like a dict : such variables tend to be “homogeneous” in some way, asking them to be used in array operations and, therefore, should probably be combined into a dedicated container instead.
0
source

Source: https://habr.com/ru/post/1237899/


All Articles