0

In my script test.py I have a lot of functions and classes and then I have the following:

for i in dir():
    if i[0] != '_':
        print(type(i), i.__doc__)

But it doesnt work because when using dir() to get a list of what is in my namespace, I get a list of strings and not objects. How can I print the docstrings of all the objects (that have docstrings) in my script?

Solution based on Ashwini Chaudhary's answer

I put this in my main() function after the module has been loaded:

# Print out all the documentation for all my functions and classes at once 
    for k, obj in sorted(globals().items()): #vars().items():
        if k[0] != '_' and hasattr(obj,'__doc__'):
#           if type(obj) != 'module' and type(obj) != 'str' and type(obj) != 'int':
                print(k, obj.__doc__)# == 'class': # or type(obj) == 'function'):
    sys.exit()

For some reason if type(obj) != 'module' is not respected so I couldnt use that as a filter to get only my own functions. But that is OK for now.

Paul H
  • 901
  • 2
  • 7
  • 12

2 Answers2

2

You can use vars().items():

for k, obj in vars().items():
    if k[0] != '_':
       print(type(obj), obj.__doc__)

help() on vars:

vars(...)
    vars([object]) -> dictionary

    Without arguments, equivalent to locals().
    With an argument, equivalent to object.__dict__.
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
  • Calling `vars().items()` at the end of my script created a `RuntimeError: dictionary changed size during iteration`, see above for what i did instead. – Paul H Feb 17 '14 at 13:40
  • @PaulH You're trying to update a dictionary while iterating over it, what will raise an error. And it is not a good idea to update `vars()` and `globals()`. – Ashwini Chaudhary Feb 17 '14 at 13:44
1

if dir is giving you the stuff you want, you can use globals to look up the objects themselves.

for i in dir():
    if i[0] != '_':
        item = globals()[i]
        print(type(item), item.__doc__)

If you want more fine control over what you get, you can use inspect.getmembers. In order to get a reference to the current module, you need sys as documented in this answer.

Community
  • 1
  • 1
mgilson
  • 300,191
  • 65
  • 633
  • 696