2

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

1
  • 6
    Are you looking for getattr? Commented Jun 11, 2020 at 13:04

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

You can do something like

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

1 Comment

What if the attribute is False? It wont enter the conditional block, but it should, because its not None.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.