3

I want to find a generic way to list a python object attributes (names and values) but in a concise way. This works pretty well when using vars(), but you can't use it if there's no __dict__; and dir() is full of uninteresting attributes.

I know that's kind of random, but PyCharm is doing something similar somehow, here's an example for the numpy ndarray object, which has no __dict__; and dir() contains 161 attributes. I tried to remove private and callable values from dir(), but still, there are dozens.

enter image description here

Any idea for how PyCharm is doing it? Is there a chance they have a special treatment for numpy objects for example?

martineau
  • 119,623
  • 25
  • 170
  • 301
Gal Shahar
  • 2,695
  • 1
  • 21
  • 29
  • 1
    The set of "uninteresting" attributes is large, but predictable. It wouldn't surprise me if they are just being filtered explicitly. – chepner Jun 21 '21 at 14:23
  • Thanks for your comment, do you have a source or an idea where or how can I find these predictable values list? @chepner – Gal Shahar Jun 21 '21 at 14:24
  • Related: https://stackoverflow.com/questions/15507848/what-is-the-correct-way-to-override-the-dir-method – jarmod Jun 21 '21 at 14:24
  • 1
    I don't think it's published, but you can construct a useful list just by looking at `dir(x)` for lots of values of `x` with different types. (Most of which, though, are CPython implementation details. It would be interesting to see what happens if you could set PyCharm to use something like `pypy`, to see if anything changes.) – chepner Jun 21 '21 at 14:26
  • That's funny I just figured out that the value that PyCharm presents (of this ndarray instance), is the value of the "real" attribute. Maybe it does hard-coded after all. @chepner – Gal Shahar Jun 21 '21 at 14:37
  • 2
    I'll bet that PyCharm has dedicated code for displaying numpy arrays, pandas series, etc. because these are popular library, rather than using a generic object decoder. – Barmar Jun 21 '21 at 15:15

1 Answers1

1

For classes defined in Python, you can use __dict__ (if any) on the object plus __slots__ on its type (if any). For built-in types in CPython, you might also want to search the class’s dictionary for objects of type types.GetSetDescriptorType, types.MemberDescriptorType, and/or types.DynamicClassAttribute. This misses most things that have __names__, though it can still be useful to filter the ones that remain.

Davis Herring
  • 36,443
  • 4
  • 48
  • 76
  • It is better now, but still many other items. Thank you for the answer! – Gal Shahar Jun 22 '21 at 08:34
  • @GalShahar: What “other items”? I’m not sure it’s possible to do better than the above without type-specific rules, but if you give an example we could find out. – Davis Herring Jun 22 '21 at 12:29