Get all @properties from a Python Class [duplicate]
Asked Answered
T

1

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?

Tile answered 21/1, 2021 at 10:1 Comment(0)
T
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)
    ]
Tile answered 21/1, 2021 at 10:1 Comment(2)
That's not going to find inherited properties. You need to traverse the whole MRO.Jewell
@user2357112supportsMonica Good point. Thanks for the hint. This was missing in the answer of #5876549 as well, so I posted an answer there.Tile

© 2022 - 2024 — McMap. All rights reserved.