0

I want to make a sort of help() function for my module. My idea is to have something like module.help() that just prints out the __doc__ of my functions. My first approach was just to hardcode them and then iterate over them, but I feel there has to be a better way to do so. I looked through the docs for a reference as to where they are stored but couldn't find any. What I want is the python equivalent to this but for function names. I would appreciate if anyone could help me out. Thanks!

Edit: Ok so as of now the functions I have are:

BoyleGraph

Boyle_Resolve

Boyle_k

Boyle_k_solve

GayLussacGraph

GayLussac_Resolve

`

and what I have tried so far is:

funcs = list()

for f in dir():
    funcs.append(f)

def helper():
    
    for f in funcs[:-13]:
        print(help(f))

and this returns something like (redacted):

No Python documentation found for 'GayLussac_Resolve'.
Use help() to get the interactive help utility.
Use help(str) for help on the str class.

Now using:

def helper():
    
    for f in funcs[:-13]:
        print(f)

will give me:

BoyleGraph
Boyle_Resolve
Boyle_k
Boyle_k_solve
GayLussacGraph
GayLussac_Resolve

but doing:

def helper():
    
    for f in funcs[:-13]:
        print(f, '\n', '#' * 50)
        print(f.__doc__)

gives me (redacted):

GayLussac_Resolve 
 ##################################################
str(object='') -> str
str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or
errors is specified, then the object must expose a data buffer
that will be decoded using the given encoding and error handler.
Otherwise, returns the result of object.__str__() (if defined)
or repr(object).
encoding defaults to sys.getdefaultencoding().
errors defaults to 'strict'.

which is the __doc__ of str() which is not even in the funcs list. I feel I'm so close yet so far.

PS: I know the funcs definition looks sloppy but when I try to assign directly or use list comprehensions I only get the first element of dir()'s output

  • 2
    I think `help()` already spits out the `__doc__` – hjpotter92 Jul 28 '20 at 19:02
  • https://docs.python.org/3/library/functions.html#help already exists. Just document your code, – Patrick Artner Jul 28 '20 at 19:05
  • @hjpotter92 well, it does a bit more magic, but yeah, it largely prints the module-level (ie `__init__.py`) docstring if it exists. If it does not, it prints all the docstrings it can find (a long with classes definitions) – DeepSpace Jul 28 '20 at 19:07

1 Answers1

1

dir() gets you a list of names, not objects. You could use the values of globals() instead, but you would need to filter out special names like __builtins__ and imports. Instead, just use help(module). It does everything you want, automatically.

wjandrea
  • 28,235
  • 9
  • 60
  • 81