1

I am new to Python and I was printing the __doc__ of various built-in Python methods. Then I tried to do the following:

for f in dir(__builtins__):
    print('********' + f + '********\n', f.__doc__)

I was surprised when the result of this looked something like this:

********abs********
    str(object='') -> str
    str(bytes_or_buffer[, encoding[, errors]]) -> str
********all********
    str(object='') -> str
    str(bytes_or_buffer[, encoding[, errors]]) -> str
********any********
    str(object='') -> str
    str(bytes_or_buffer[, encoding[, errors]]) -> str
********ascii********
    str(object='') -> str
    str(bytes_or_buffer[, encoding[, errors]]) -> str

After doing some research, I found this, but I still didn't see how I could do what I was hoping to accomplish. I know that this is seamlingly pointless, but I feel it will be useful for me to understand how to dynamically execute tasks similar to this in Python.

Thank you for the help!

U13-Forward
  • 69,221
  • 14
  • 89
  • 114
Anguna
  • 170
  • 2
  • 9

2 Answers2

4

dir(__builtins__) (also iterating over a module) gives the names in the module to get the objects one has to use getattr:

for f in dir(__builtins__):
    print('********' + f + '********\n', getattr(__builtins__, f).__doc__)
Dan D.
  • 73,243
  • 15
  • 104
  • 123
1

In your for loop, you are not getting the actual functions/methods when you call

for f in dir(__builtins__):

Instead, each time f is just a string with the name of the function/method. So when you call:

f.__doc__

You are always getting back the docstring for str types. It is no different than calling:

'abc'.__doc__
James
  • 32,991
  • 4
  • 47
  • 70