Function or script on LHS of the equation in python

55 views Asked by At

I have a requirement on cocotb similar to below :

x = "a"
x = 2 => This should become a = 2

Can someone please help whether would it be possible to achieve this in python ? I need to assign values to DUT (like below) based on the above approach:

for sig in ["sig_1", "sig_2"]:
    self.bfm.sig = 1
3

There are 3 answers

2
Drphoton On BEST ANSWER

I’m pretty sure you don’t want to be doing this in your code, but what you are trying to do can be accomplished using eval():

for sig in ["sig_1", "sig_2"]:
    eval(f”self.bfm.{sig} = 1”)

This will also work with your MWE at the top of your question:

x = "a"
eval(f”{x} = 2”)

Note that this kind of use (or abuse) of eval goes against best practices. You’d probably be better off turning bfm into a dict, which is frankly made to accept strings as keys in the way you are trying to use them:

for sig in ["sig_1", "sig_2"]:
    self.bfm[sig] = 1
0
Talha Tayyab On

as Unmitigated commented:

for sig in ["sig_1", "sig_2"]:
    self.bfm[sig]=1

should do if you want 1 for both of them "sig_1", "sig_2"

0
Unmitigated On

Use square brackets.

for sig in ["sig_1", "sig_2"]:
    self.bfm[sig] = 1