How do you get a list of objects in a script so that you can print __doc__ on each of them?

StackOverflow https://stackoverflow.com/questions/21730066

  •  10-10-2022
  •  | 
  •  

Pergunta

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.

Foi útil?

Solução

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__.

Outras dicas

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.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top