How to dynamically generate a string in Python (observer pattern)
Let's assume we have the code below:
var1="top"
var2=var1+"bottom"
We want to change the value var1
if the condition is true:
if COND==True:
var1="changed"
Now I want to have var2
dynamically changed . The code above var2
will still have the value " topbottom
".
How can i do this?
thank
source to share
You can use string formatting to specify a placeholder in var2
where you want to place the updated value var1
:
In [1653]: var2 = '{}bottom'
Placeholder is {}
indicated in parentheses . Then call var2.format
to insert var1
in var2
as 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'
source to share
You can achieve this elegantly with a ProxyTypes
package callback proxy :
>>> from peak.util.proxies import CallbackProxy
>>> var2 = CallbackProxy(lambda: var1+"bottom")
>>> var1 = "top"
>>> var2
'topbottom'
>>> var1 = "left"
>>> var2
'leftbottom'
Every time you access yours var2
, the lambda callback is executed and a dynamically generated value is returned.
source to share
There is no easy way to do this as the string is immutable in python. Cannot be changed var2
after evaluation var1+"bottom"
. You either need to create a new line (not sure why you don't want to do this), or you need to write your own class and create your own objects that agree with this behavior. If you want to do this, see Observer Template
source to share