Supposing we have the code below:
var1="top"
var2=var1+"bottom"
We want to change var1 value if a condition is true:
if COND==True:
var1="changed"
Now I want to have var2 dynamically changed. With the code above, var2 will still have the value "topbottom".
How can I do that?
Thanks
You can elegantly achieve this with a callback proxy from ProxyTypes package:
>>> from peak.util.proxies import CallbackProxy
>>> var2 = CallbackProxy(lambda: var1+"bottom")
>>> var1 = "top"
>>> var2
'topbottom'
>>> var1 = "left"
>>> var2
'leftbottom'
Each time you access your var2, callback lambda will be executed and a dynamically generated value returned.
You can use string formatting to specify a placeholder in var2 where you want the updated value of var1 to be placed:
In [1653]: var2 = '{}bottom'
The {} brackets here specify a placeholder. Then call var2.format to insert var1 into var2 as and when needed.
In [1654]: var1 = 'top'
In [1655]: var2.format(var1)
Out[1655]: 'topbottom'
In [1656]: var1 = 'changed'
In [1657]: var2.format(var1)
Out[1657]: 'changedbottom'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With