Python check if attribute is none depending on string

Viewed 1189

I want to check if an attribute from a class is None. The attribute itself depends on some cases and is stored in a string "attribute_name". How can I check of the attribute is None? Something like:

hasattr(object, attribute_name)

but then not checking of the attribute exists in the model but if it has a value

2 Answers

You can use hasattr to check if the object has the specific attribute and need to check if the attribute value is None or not. So you can do this as following

hasattr(object, attribute_name) and getattr(object, attribute_name) is None

I hope this will help you.

You can do something like

if getattr(object, attribute_name) is not None:
    # Your code here
Related