2

In Python, how can I get all properties of a class, i.e. all members created by the @property decorator?

There are at least two questions[1, 2] on stackoverflow which confound the terms property and attribute, falsely taking property as a synonym for attribute, which is misleading in Python context. So, even though the other questions' titles might suggest it, they do not answer my question.


[1]: Print all properties of a Python Class
[2]: Is there a built-in function to print all the current properties and values of an object?

Jonathan Scholbach
  • 4,925
  • 3
  • 23
  • 44

1 Answers1

0

We can get all attributes of a class cls by using cls.__dict__. Since property is a certain class itself, we can check which attributes of cls are an instance of property:

from typing import List


def properties(cls: type) -> List[str]:
    return [
        key
        for key, value in cls.__dict__.items()
        if isinstance(value, property)
    ]
Jonathan Scholbach
  • 4,925
  • 3
  • 23
  • 44
  • 1
    That's not going to find inherited properties. You need to traverse the whole MRO. – user2357112 Jan 21 '21 at 10:04
  • @user2357112supportsMonica Good point. Thanks for the hint. This was missing in the answer of https://stackoverflow.com/questions/5876049/in-a-python-object-how-can-i-see-a-list-of-properties-that-have-been-defined-wi as well, so I posted an answer there. – Jonathan Scholbach Jan 21 '21 at 10:24