Fluffy Fluffy - 24 days ago 5x
Python Question

What should I use instead of assignment-in-an-expression in Python?

according to this page one can't use code like

if variable = something():
#do something with variable, whose value is the result of something() and is true

So in case I want to have the following code structure:

if a = something():
#do something with a
elif a = somethingelse():
#5 more elifs

where something() functions are compute-intensive (I mean that using the function and then doing it again to assign value to a variable in case the first one was true can't be done), what should I write instead in Python? Add 7 more variables instead of 1?


I had this problem years ago, in 2001 -- since I was transliterating to Python from a reference-algorithm in C which used assign-and-test heavily, I was keen to keep a similar structure for the first draft (then refactor later once correctness was well tested). So I wrote a recipe in the Cookbook (see also here), which boils down to...:

class DataHolder(object):
    def set(self, value): self.value = value; return value

so the if/elif tree can become:

dh = DataHolder()
if dh.set(something()):
  # do something with dh.value
elif dh.set(somethingelse()):
  # ...

the DataHolder class can clearly be embellished in various ways (and is so embellished in both the online and book versions), but this is the gist of it, and quite sufficient to answer your question.