0

This solution seemed like it would help solve my problem: Getting attributes of a class

However, when I follow the steps linked above, my project only returns Config and fields. This is likely because these classes inherit from Pydantic's BaseModel.

What I'm looking for is for a class, say:

class GameStatistics(BaseModel):
    id: UUID
    status: str
    scheduled: datetime

I should return id, status, and scheduled.

My attempt:

for name, cls in inspect.getmembers(module, lambda member: inspect.isclass(member) and member.__module__== module.__name__):

    for _name, attrbs in inspect.getmembers(cls, lambda member: not(inspect.isroutine(member))):
        if not _name.startswith('_'):
            print(_name, attrbs)
Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
Hofbr
  • 868
  • 9
  • 31
  • 1
    *I follow the steps linked above* then please provide piece of code which *only return Config and fields* – Daweo Jul 22 '21 at 14:33
  • 1
    How about `GameStatistics.__fields__` – alex_noname Jul 23 '21 at 08:02
  • 2
    If you need this info for objects of this class, all you need is `object.dict()`. But if you want something for the class itself, that's more complicated. – Mike B Jul 27 '21 at 00:19
  • Are you specifically looking for a solution that doesn't use Pydantic/BaseModel's "magic" methods and properties? Purely Python class methods and properties? – Gino Mempin Jun 02 '22 at 02:12

2 Answers2

2

Try

for field in GameStatistics.__fields__:
    print(field)
Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
victorkolis
  • 780
  • 13
  • 13
1

List comprehension would be a cleaner way to do this if you want to do something with the value.

[field for field in GameStatistics.__fields__.keys()]

or just

list(GameStatistics.__fields__.keys())
Lloyd Hamilton
  • 101
  • 1
  • 3