1

While reading some Python training books, I was tinkering a little bit with objects, like printing docstrings for common objects and attributes.

Consider the list of strings returned by:

dir(str)

I am trying to iterate over the above in order to dynamically print the docstrings of the attributes stored in the dir list with the following loop:

for item in dir(str):
    print(item.__doc__)

This returns the dir output for the str object and not for its attribute though, which is not what I'm looking for. How can I dynamically print instead the docstring for all the attributes that populate the list produced by the dir method?

EDIT: this is NOT a duplicate of this other question. Using the word "enumerate" is very misleading, at least to me, so I would say that question is improperly titled in fact I spent a lot of time looking for a solution and no search query ever returned that.

alfx
  • 174
  • 2
  • 14
  • 1
    Possible duplicate of [How to enumerate an object's properties in Python?](https://stackoverflow.com/questions/1251692/how-to-enumerate-an-objects-properties-in-python) – Aran-Fey Oct 05 '17 at 10:59
  • using the word "enumerate" is very misleading, at least to me, so I would say that question is improperly titled in fact I spent a lot of time looking for a solution and no search query ever returned that – alfx Oct 05 '17 at 12:36

2 Answers2

1

You can use getattr(obj, attr) to get the named attribute from the object.

for item in dir(str):
    print(getattr(str, item).__doc__)
khelwood
  • 55,782
  • 14
  • 81
  • 108
1

Instead of using dir, which just gives you the names of attributes, use vars - this gives you a dict of names to the actual method objects.

for name, method in vars(str).items():
    print(name, method.__doc__)
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • thanks this works as well as the reply from khelwood. I find though that there is no need to invoke this dictionary because you get the same results by: `for item in dir(var): print(item, '\n', getattr(str, item).__doc__)` thanks a lot. this being said, in your opinion, should I still pick the dict way? – alfx Oct 05 '17 at 13:48