user3541631
user3541631

Reputation: 4008

Get the value of an obj attribute knowing its name

I have a number of constants,variable in which i keep names.

ATTR_ITEM_NAME = 'pro'

I check if the attribute is attached to an objects:

 if hasattr(obj1, ATTR_ITEM_NAME):

then if exist I want the attribute value to be passed to an attribute of an object, something like this:

obj2.fm = obj1.ATTR_ITEM_NAME

ATTR_ITEM_NAME being a string and not an attribute is an error, I need something that works;

Upvotes: 1

Views: 54

Answers (1)

hiro protagonist
hiro protagonist

Reputation: 46869

Python also has getattr which works like hasattr but returns the value:

obj2.fm = getattr(obj1, ATTR_ITEM_NAME)

If you are not sure the attribute exists you could:

  • assign a default value (e.g. None)

    DEFAULT = None
    obj2.fm = getattr(obj1, ATTR_ITEM_NAME, DEFAULT)
    
  • or catch the exception using

    try:
        obj2.fm = getattr(obj1, ATTR_ITEM_NAME)
    except AttributeError:
        pass  # or do something else...
    

Upvotes: 3

Related Questions