Home > OS >  Check the value of all properties ('@property') on a class
Check the value of all properties ('@property') on a class

Time:02-16

Using Python 3.8, I wish to identify methods decorated with @property and then check the values of those properties to ensure that all of them have a string value, not None.

My rationale for this that going forward more @property methods will be added, and I'd prefer to not have to update the validate function to get and test the value for each one, so I'm looking for a way to somewhat automate that process.

I've been able to identify all properties using the answer to this question.

props = inspect.getmembers(type(self), lambda o: isinstance(o, property))

However, I'm not to sure how to proceed with the list of tuples that has been returned.

[('certificate', <property object at 0x7f7aaecec400>), ('protocol', <property object at 0x7f7aac7d2f90>), ('url', <property object at 0x7f7aac7da040>)]

Using the list of tuples in props, is there a way to call the properties and check the values?


My solution

Thanks to the accepted answer, this is my solution.

class MyClass:

    # Methods removed for brevity.

    def _validate(self) -> None:
        props = inspect.getmembers(type(self), lambda o: isinstance(o, property))
        invalid_props = [p for p, _ in props if getattr(self, p) is None]
        if invalid_props:
            raise MyException(invalid_props)

CodePudding user response:

You could use getattr with the property names in the props tuple.

valid = [p for p, _ in props if getattr(self, p) is not None]

Remember that accessing a property may execute arbitrary code, so the getting of the value itself might set the value to None or not None.

  • Related