1

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)
David Gard
  • 11,225
  • 36
  • 115
  • 227
  • 3
    For the identifying properties part this question might be useful: [python inspect get methods decorated with @property](https://stackoverflow.com/questions/34498237/python-inspect-get-methods-decorated-with-property)? – timgeb Feb 15 '22 at 16:14
  • @timgeb, thanks for that link, that's a good start. I'll try and work a solution from that. – David Gard Feb 15 '22 at 16:41
  • Does this answer your question? https://stackoverflow.com/questions/1167398/python-access-class-property-from-string – Pranav Hosangadi Feb 15 '22 at 17:10
  • @PranavHosangadi, thanks was helpful. It hadn't occurred to me that a I could use `getattr()` with a property in this way. – David Gard Feb 16 '22 at 09:34

1 Answers1

1

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.

timgeb
  • 76,762
  • 20
  • 123
  • 145
  • Thank you, other than checking for `is None` so that I find invalid properties, that is perfect. In my case the properties are literally just returning a value so there should be no chance of arbitrary code being executed. – David Gard Feb 16 '22 at 09:32