Setting an attibute of an object as a String

Hello everyone, I hope you’re doing well ! I am actually looking for a certain thing to do.

I have a certain object “uut.adder” that might have a hundred different attributes (example: uut.adder.c1,uut.adder.b1, uut.adder.a3 and so on) so I would like to loop over ALL THESE so I’m trying to find a way to GET all of them so I can loop over all of them

Hello, I think you are looking for these three builtin functions:

class ClassA:

obj = ClassA()
obj.attr1 = 1
obj.attr2 = 'hello'

print(dir(obj))               # Get list of object's attributes.
            # You may want to filter the "dunder" (double-underscore) attributes.
setattr(obj, 'attr1', 7)      # Set attribute's value.
print(getattr(obj, 'attr2'))  # Get attribute's value.


['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'attr1', 'attr2']

Thank you for your answer Vaclav !

Actually it’s weird because getattr(uut.adder,“c”) works when I wanna do something
but dir(uut.adder) returns a Cocotb error saying Failed to cast handle, I know it’s not a python error

It looks like Cocotb does something weird. dir() should work on all Python objects. None of these fails:

for item in (None, True, object(), 1, 0.1, '', (), [], {}):

You can also try to call the method __dir__() directly on the object but I am afraid it will fail the same way:

obj = 'any object except class'

Yes I actually have the same error, maybe it’s because uut.adder is a cocotb object, it is not a python object so we cannot manipulate it the same way, (even if we are on python)