Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate string dynamically in Python (Observer Pattern)

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

like image 460
Duke Nukem Avatar asked Apr 06 '26 15:04

Duke Nukem


2 Answers

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.

like image 161
randomir Avatar answered Apr 09 '26 04:04

randomir


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'
like image 38
cs95 Avatar answered Apr 09 '26 03:04

cs95