I'd like to return the help text for each function in a given module (for example os). The code below (Code Block A) returned the following error:
AttributeError: module 'os' has no attribute 'i'
#Code block A
import os
for i in dir(os):
print (help(os.i))
If instead I run the code below (Code Block B), the function name in the ith position is returned at each step in the for loop.
#Code block B
for i in dir(os):
print (i)
Q1. Why is the index variable i recognized as "i" in Code Block A "help(os.i)", but not in Code Block B "print(i)?
Q2. Is there a way to call each item in an iterable as a function (something akin to Code Block A) for a given module?
Thanks in advance for any insights or recommendations.
There are a handful of occasions in python where the i
variable that would otherwise represent an iterable, is instead treated as the string literal "i". In those cases, it is best to build a string by adding the iterable (represented by i
) cast as a string to whatever else you were trying to add it to. Then you just feed the entire string into the function as needed.
In your particular case:
for i in dir(os):
s = "os." + str(i)
print(help(s))