Function or script on LHS of the equation in python

Question:

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
Asked By: Somesh

||

Answers:

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"

Answered By: Talha Tayyab

Use square brackets.

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

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
Answered By: Drphoton
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.